Chapter 7.
Advanced Strings, Lists
Python and Data Types
• Any kind of data can be stored in a variable.
x = 10
print("x =", x)
x = 3.14
print("x =", x)
x = "Hello World!"
print("x =", x)
x = 10
x = 3.14
x = Hello World!
String
• Any kind of data can be stored in a variable.
1. Numbers are important to computers, but text is important to
humans.
2. (Example) Text messages, Internet domain names
3. Computer-assisted text processing is also very important.
String
String
• A string is a sequence of characters.
String
• Double quotes
• Single quotes
>>> "Hello"
'Hello'
>>> msg = "Hello"
>>> msg
'Hello'
>>> print(msg)
Hello
Grammatical errors
• It is a grammatical error to start with a double quotation
mark (") and end with a single quotation mark (').
>>> msg = "Hello'
SyntaxError: EOL while scanning string literal
Just like English
has grammar
errors, Python
also has
grammar errors.
Difference between 100 and “100”
• 100 -> Integer
• “100”, ‘100’ -> String
>>> print(100+200)
300
>>> print("100"+"200")
100200
If you do 100+200, it becomes (integer+integer) and
can be added. However, since “100”+”200” adds text
to text, it just ends up as two texts stuck together.
string -> number
• int(): Convert string to integer
• float(): Convert string to float
t = input("Enter an integer: ")
x = int(t)
t = input("Enter an integer: ")
y = int(t)
print(x+y)
Enter an integer: 100
Enter an integer: 200
300
number->string
• Why does the following code cause an error?
>>> print('I am currently' + 21 + 'years old.')
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
print('I am currently ' + 21 + 'years old.')
TypeError: Can't convert 'int' object to str implicitly
This means that strings and numbers cannot be combined.
number->string
• Using the str() function
>>> print('I am currently ' + str(21) + ' years old.')
I am currently 21 years old.
>>> print('The pi is ' + str(3.14) + '.')
The pi is 3.14.
str()
Oh~
String concatenation
• To concatenate two strings -> + operator
>>> 'Hello ' + 'World!'
'Hello World!'
String repetition
• To repeat a string, use the ->* operator.
>>> message = " Congratulations!"
>>> print(message*3)
Congratulations!Congratulations!Congratulations!
>>> print("="*50)
==================================================
Include variable values in strings
• If you want to insert the value of a variable into a string
and print it out, use the ->% symbol.
>>> price = 10000
>>> print("The price of the product is %s won." % price)
The price of the product is 10000 won.
Extract individual characters
• To extract individual characters from a string, -> we use
numbers called indices.
s = "Monty Python"
print(s[6:10])
Pyth
Special strings
특수 문자열 의미
\n Line break character
\t Tab character
\\ Backslash itself
\" The double quotes themselves
\' The single quote itself
>>> print("With a single word,\nI pay off a thousand nyang of debt")
With a single word,
I pay off a thousand nyang of debt
Lab: A friendly conversation program
• Let's write a program that uses variables to store a user's
name and age in string form and then prints it out.
Hello?
What is your name? Asema
Nice to meet you, Asema
Your name is: 5
How old are you? 21
You will be 22 next year.
>>>
• When calculating the length of a string, use len(s).
Solution
print('Hello?')
name = input('What is your name? ')
print('Nice to meet you.' + name)
print('The length of your name is:', end=' ')
print(len(name))
age = int(input("How old are you? "))
print("Next year", str(age+1), ", you will be.")
Challenge problem
Ask the user other questions and respond in a friendly way. For example, you could ask about
hobbies like this:
"What are your hobbies?" "Watching movies."
"Yes, I like watching movies too."
Lab: Print the sum of year, month, and day
• Let's write a program that adds up the year, month, and
day of the day that the user inputs and displays them on
the screen, using a variable that stores a string.
Enter today's year: 2024
Enter today's month: 09
Enter today's day: 10
Today is 09-10-2024.
Solution
year = input("Enter today's year: ")
month = input("Enter today's month: ")
date = input("Enter today's day: ")
print("Today is", month+"-", date+"-", year+".")
Lab: How old will you be in 2050?
• Let's write a program that calculates how old you will be in
2050.
This year is 2016.
Are you a dead person? 11
You will be 55 years old in 2050.
import time
now = [Link]()
thisYear = int(1970 + now//(365*24*3600))
print("This year is " + str(thisYear)+".")
Solution
import time
now = [Link]()
thisYear = int(1970 + now//(365*24*3600))
print("This year is " + str(thisYear)+".")
age = int(input("How old are you? "))
print("In 2050, you will be "+str(age + 2050-thisYear)+" years old.")
Challenge problem
Is it possible to print a variable and a string at the same time using commas, such as
print("This year is", thisYear, ".") without using str()? Let's change the above program like this.
Which method is more convenient?
List
• In some cases, it is necessary to store multiple pieces of
data together.
Iron Man
Thor
heroes = ["Iron Man", "Thor", "Hulk", "Scarlet Witch"
Hulk
Scarlet Witch
Add from blank list
>>> heroes = [ ]
>>> [Link]("Iron Man")
['Iron Man']
>>> [Link]("Doctor Strange")
>>> print(heroes)
['Iron Man', 'Doctor Strange']
>>>
Meaning of dots
• In Python, everything is an object. An object is a group of
related variables and functions. In Python, lists are also
objects.
• When using something inside an object, you write the
name of the object followed by a period (.) and then the
name of the function.
[Link]("Ion Man")
Accessing list items
>>> letters = ['A', 'B', 'C', 'D', 'E', 'F']
>>> print(letters[0])
A
>>> print(letters[1])
B
>>> print(letters[2])
C
Slicing
• Slicing is a technique for extracting multiple items from a
list at once.
>>> letters = ['A', 'B', 'C', 'D', 'E', 'F']
>>> print(letters[0:3])
['A', 'B', 'C']
Omit index
>>> print(letters[:3])
['A', 'B', 'C']
>>> print(letters[3:])
['D', 'E', 'F']
>>> print(letters[:])
['A', 'B', 'C', 'D', 'E', 'F'] 리스트를 복사할 때 사용한다.
Change list items
>>> heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
>>> heroes[1] = "Doctor Strange"
>>> print(heroes) Use index.
['Iron Man', 'Doctor Strange', 'Hulk', 'Scarlet Witch']
>>>
Add using functions
>>> [Link]("Spider-Man")
>>> print(heroes)
['Iron Man', 'Doctor Strange', 'Hulk', 'Scarlet Witch', 'Spider-Man']
>>> [Link](1, "Batman")
>>> print(heroes)
['Iron Man', 'Batman', 'Doctor Strange', 'Hulk', 'Scarlet Witch', 'Spider-Man']
>>>
Delete an item
heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
[Link]("Scarlet Witch")
print(heroes)
['Iron Man', 'Thor', 'Hulk']
Check if an item is in a list
if "superman" in heroes:
[Link]("superman")
del
• del deletes an item using its index.
heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
del heroes[0]
print(heroes)
['Thor', 'Hulk', 'Scarlet Witch']
del
• pop() removes the last item from the list
heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
last_hero = [Link]()
print(last_hero)
Scarlett Witch
Browse the list
• Using index()
heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
print([Link]())
2
Visit the list
• pop() removes the last item from the list
heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
for hero in heroes:
print(hero)
Iron Man
Thor
Hulk
Scarlet Witch
Sort the list
heroes = [ "Iron Man", "Thor", "Hulk", "Scarlet Witch" ]
[Link]()
print(heroes)
['Scarlet Witch', 'Iron Man', 'Thor', 'Hulk']
Lab: Proverb of the day
• After saving several proverbs in the list, one of the
proverbs is randomly selected and provided as the proverb
of the day.
##############################
# Proverb of the day #
##############################
There is nothing truly valuable that can be obtained without suffering.
Have a dream. Then you can overcome
the difficult reality.")
Anger lives only in
When a person loves,
the hearts of fools..
everyone becomes a poet.
The beginning is half.
Solution
import random
quotes = []
[Link]("Have a dream. Then you can overcome the difficult reality.")
[Link]("Anger lives only in the hearts of fools..")
[Link]("There is nothing truly valuable that can be obtained without suffering.")
[Link]("When a person loves, everyone becomes a poet.")
[Link]("The beginning is half.")
dailyQuote = [Link](quotes)
print("############################")
print("# Today's Proverb #")
print("################################")
print("")
print(dailyQuote)
What we learned in this chapter
• We learned about strings and lists in depth.
• In the concept of combining strings and
numbers, in addition to the + operator, the
* operator can also be used.
• You can slice the length of the string and
the desired section.
• If you use a dot in a list, you can use various
functions.
• You can easily handle adding, modifying,
and deleting values.