chapter 3.1

Strings & Input

Manipulating text and reading user input

Strings are everywhere in programming — names, messages, file paths, URLs. Python gives you powerful tools to work with them.
f-strings are the cleanest way to mix variables into text. Prefix the string with f and put variables inside {}:
name = "Ada"
age = 28
print(f"My name is {name} and I am {age} years old")
print(f"Next year I will be {age + 1}")
tip
Always use f-strings for string formatting. Older methods like % and .format() still work but f-strings are cleaner and faster.
Indexing and slicing let you pull out parts of a string. Python counts from 0:
word = "Python"
print(word[0])      # P (first character)
print(word[-1])     # n (last character)
print(word[0:3])    # Pyt (characters 0, 1, 2)
print(word[2:])     # thon (from index 2 to end)
String methods — strings come with built-in functions you call with a dot:
msg = "  Hello, World!  "
print(msg.upper())          # "  HELLO, WORLD!  "
print(msg.lower())          # "  hello, world!  "
print(msg.strip())          # "Hello, World!" (removes whitespace)
print(msg.replace("World", "Python"))
print("hello".startswith("he"))  # True
print(len(msg))             # 17
Getting input from the user with input():
name = input("What is your name? ")
print(f"Hello, {name}!")
warning
input() always returns a string — even if the user types a number. To do math with it, convert it: age = int(input("Age? "))
your turn
challenge

Use `input()` to ask for the user's name, then print: 1. The name in all uppercase 2. The first 3 characters 3. The length of the name using `len()` 4. A greeting using an f-string

loading editor...

output
$ Press RUN to execute your code
AI Tutor

Ask about Strings & Input

Hey! I'm your AI tutor.

Ask me anything about this lesson, or paste code you're stuck on.

AI tutor is a premium feature