All coding lessonsLesson 8 of 10

Strings, Input and Files

Working with text and talking to the outside world

Strings are immutable sequences

text = "Python is fun"
print(text[0], text[-3:])
print(len(text))
print(text.upper(), text.lower(), text.title())
print(text.replace("fun", "powerful"))
print(text.split())          # [Python, is, fun]
print("-".join(["a", "b"]))  # a-b
print("  trim me  ".strip())

Every string method returns a new string; the original never changes. That is what immutable means.

Useful checks

print("42".isdigit())       # True
print("abc".startswith("a"))# True
print("Fun" in text)        # False (case sensitive)
print(text.find("is"))      # 7, or -1 if missing

Formatting numbers with f-strings

pi = 3.14159265
print(f"{pi:.3f}")     # 3.142
print(f"{1234567:,}")  # 1,234,567
print(f"{0.256:.1%}")  # 25.6%
print(f"{"left":<10}|")

Reading user input

name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"In ten years {name} will be {age + 10}.")

input() always returns a string, even when the user types digits. Convert it before doing arithmetic.

Files: always use with

with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    f.write("second line\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())

The with statement is a context manager: it closes the file automatically, even if an error happens inside the block. Modes are "r" to read, "w" to overwrite, "a" to append.

Ask Teacher Smith questions about this Python lessonOpens your AI tutor with a question about “Strings, Input and Files” →