edubun
English

Strings: working with text

Python counts the letters of "Python" from 0, so "Python"[5] is the last letter, n, and "Python"[6] is an error.

A name tag needs text built from pieces

Think of the name tags at a school event or a club meeting. Every tag has the same layout and a different name, so a program can print them all from one pattern. Text in Python is a string, and the quickest way to build one out of pieces is an f-string: put the letter f in front of the opening quote and write variable names inside curly braces. Python swaps each {name} for the value of that variable.

name = "Mina"
club = "Robotics"
print(f"Hello, {name}!")
print(f"{name} joined {club}.")
Output
Hello, Mina!
Mina joined Robotics.

There are two older ways to join text. The + operator glues strings end to end, and * repeats a string. Both sides of + must be strings, so a number has to be turned into text with str() first. f-strings do that conversion for you, which is one reason they are the usual choice.

item = "gimbap"
count = 2
print(item + " x " + str(count))
print("-" * 12)
print(f"{item} x {count}")
Output
gimbap x 2
------------
gimbap x 2

Each character has a position number, starting at 0

A string is a row of characters, and each one has an index. The first character is at index 0, not 1. Square brackets pick one character: word[0] is the first. Negative indexes count from the end, so word[-1] is always the last character, whatever the length. len() gives the number of characters, spaces and punctuation included.

Index numbers for "Python": 0 to 5 from the front, -6 to -1 from the back. A slice word[0:2] stops before index 2.
word = "Python"
print(word[0], word[5], word[-1])
print(len(word))
print(word[0:2], word[2:])
Output
P n n
6
Py thon

word[0:2] is a slice: it starts at index 0 and stops just before index 2, giving "Py". Leave out the end, as in word[2:], and the slice runs to the end of the string. The stop-before rule looks odd at first, but it means word[0:2] + word[2:] always gives back the whole word.

String methods return a new string

Strings come with built-in tools called methods, written after a dot. upper() and lower() change the case, replace(old, new) swaps every copy of one piece of text for another, and strip() removes spaces from both ends, which helps when someone types an extra space into a form. The keyword in checks whether one string appears inside another and gives True or False. None of these change the original string. A string cannot be changed after it is made; each method hands back a new one, and you keep it by assigning it to a name.

menu = "  tteokbokki  "
clean = menu.strip()
print(clean.upper())
print(clean.replace("k", "K"))
print("bok" in clean, len(menu), len(clean))
Output
TTEOKBOKKI
tteoKboKKi
True 14 10

To put a quote mark inside a string, use the other kind of quote around it: "It's fine". A backslash starts an escape sequence: \n inside a string means "start a new line here", so one print can show two lines.

print("It's lunch time.")
print("Line one\nLine two")
Output
It's lunch time.
Line one
Line two
f-stringf"...{name}..." puts values into text
indexPosition number of a character, starting at 0
slices[a:b]: from index a up to but not including b
len()Number of characters in a string
methodA tool written after a dot, such as s.upper()
\nEscape sequence for a new line
in"a" in "cat" gives True
  1. What does this print?
    word = "banana"
    print(word[1])
  2. What does this print?
    word = "banana"
    print(word[-2])
  3. What does this print?
    print(len("Hi there!"))
  4. What does this print?
    word = "school"
    print(word[1:4])
  5. What does this print?
    name = "Jun"
    print(f"Hi {name}, you are {13 + 1}.")
  6. What does this print?
    print("ab" * 3)
  7. What does this print?
    s = "hello"
    s.upper()
    print(s)
    • HELLO
    • hello
    • Hello
    • An error
  8. What does this print?
    print("rice" in "fried rice")
  9. What does this print?
    name = "Mina"
    print(f"{name}")
    print("{name}")
    • Mina
      Mina
    • Mina
      {name}
    • {name}
      Mina
    • {name}
      {name}
  10. What does this print?
    print("Total: " + str(3 * 1000))
    • Total: 3000
    • Total: 3 * 1000
    • Total: 31000
    • An error
Common mistakes
  • "The first letter is word[1]." Indexes start at 0, so word[1] is the second letter. The last valid index is len(word) - 1; "Python"[6] stops with IndexError: string index out of range.
  • "Age: " + 15 prints Age: 15 A string and an int cannot be joined with +. Python stops with TypeError: can only concatenate str (not "int") to str. Use str(15) or an f-string.
  • "I can fix one letter with word[0] = "J"." Strings cannot be changed in place: TypeError: 'str' object does not support item assignment. Build a new string instead, for example "J" + word[1:].
Teacher's noteCounting from 0 needs a picture, not a rule. Draw the boxes with numbers above and below, as in the figure, and have learners point to word[2] and word[-2] before typing anything. Slices are easier once they see the numbers as fences between boxes rather than labels on boxes. The upper() trap (calling a method and not keeping the result) comes back with lists, so spend a minute on it now. On Korean Windows fonts the backslash may display as the won sign; it is the same key and the same character to Python.
Key points
  • f"...{x}..." puts values into text.
  • Indexes start at 0; -1 is the last character.
  • s[a:b] runs from a up to, not including, b.
  • Methods such as upper() return a new string; the original is unchanged.
  • "\n" is a line break inside a string.
Sources for this course (6)
  • Python Software Foundation, The Python Tutorial for Python 3.12 (docs.python.org/3.12/tutorial: 2 Using the Python Interpreter, 3 An Informal Introduction to Python (numbers, text, lists), 4 More Control Flow Tools (if, for, range, break and continue, defining functions, default argument values, 4.10 coding style: 4-space indentation), 5 Data Structures (list methods, 5.5 dictionaries, insertion order), 8 Errors and Exceptions (syntax errors, exceptions, reading the traceback, handling exceptions), 15 Floating-Point Arithmetic (0.1 + 0.2))
  • Built-in Functions (docs.python.org/3.12/library/functions.html: print, input, len, int, float, str, type, round (round half to even: round(0.5) and round(-0.5) are 0, round(1.5) is 2), range, sum, min, max, sorted)
  • Built-in Types (str methods upper, lower, replace, strip; dict.get; list.append, pop, remove, sort returning None)
  • General Python FAQ (docs.python.org/3.12/faq/general.html: Guido van Rossum began Python in the 1989 Christmas holidays, posted it to USENET in February 1991, named it after Monty Python's Flying Circus)
  • Curriculum for the Korean pages: 교육부 고시 제2022-33호 [별책 10] 정보과 교육과정 (PDF read 2026-10-19: 중학교 정보 [9정03-05] 리스트 등 데이터를 순차적으로 저장하는 구조, [9정03-06] 논리 연산과 중첩 제어 구조, [9정03-07] 함수 활용과 디버거로 오류 수정, [9정03-08] 실생활 문제를 프로그래밍으로 해결, 적용 시 고려 사항 「학생의 수준을 고려하여 적합한 프로그래밍 언어를 선정」; 고등학교 정보 [12정03-04] 자료형, [12정03-05] 표준입출력, [12정03-07] 제어 구조)
  • Bug story only: Smithsonian National Museum of American History, Log Book With Computer Bug, 1947, Harvard Mark II, "first actual case of bug being found", probably not Hopper's log book (americanhistory.si.edu/collections/object/nmah_334663, read 2026-10-19)

Checked: 2026-10-19