PyComplete Python Course
Beginner 45 min

Module 03 β€” Strings & User Input

Slicing, formatting, and reading what the user types.

Prerequisite: Module 02 β€” Print & Basic Output

After this lesson, you will be able to

  • Read a value typed by the user with input(), and convert it with int()/float()
  • Build strings with concatenation and f-strings
  • Index and slice strings to extract characters and substrings
  • Use common string methods: strip(), find(), replace(), center()

Concept & Syntax

Strings are how Python represents text, and almost every real program needs to accept input from a person. input() pauses your program, waits for the user to type something and press Enter, and returns exactly what they typed β€” as a string, always. That last point trips up nearly every beginner at least once: if you ask for someone's age and plan to do math with it, you must convert it first.

Strings in Python are also sequences β€” ordered collections of characters β€” which means every character has a numbered position (its index), starting at 0. That's what makes slicing possible.

Syntax
name = input("Prompt: ")
age = int(input("Age: "))
greeting = f"Hello, {name}!"
first_three = name[0:3]

Examples

Reading input Very Easy

Reading input
name = input("What is your name? ")
print("Hello, " + name + "!")
OutputWhat is your name? (waits for typing) β†’ Hello, Ada!

input() always returns a string, even if the user types digits.

Converting input to numbers Easy

Converting input to numbers
age = int(input("Age: "))
next_year = age + 1
print("Next year you will be", next_year)
OutputAge: 25 β†’ Next year you will be 26

int() converts a numeric string like "25" into the integer 25. Without it, age + 1 would crash.

f-strings Easy

f-strings
name = "Ada"
score = 97.5
print(f"{name} scored {score}%")
print(f"Rounded: {score:.0f}%")
OutputAda scored 97.5% Rounded: 98%

An f-string (prefix f) lets you embed variables directly inside {curly braces}, including format specifiers like :.0f for rounding.

Indexing and slicing Intermediate

Indexing and slicing
name = "Python"
print(name[0])
print(name[-1])
print(name[1:4])
print(name[::2])
OutputP n yth Pto

Index 0 is the first character, -1 is the last. [1:4] takes indices 1 up to (not including) 4. [::2] takes every 2nd character using a step.

Useful string methods Real World

Useful string methods
raw = "  ada@example.com  "
clean = raw.strip()
print(clean)
print(clean.find("@"))
print(clean.replace("example", "python"))
Outputada@example.com 3 ada@python.com

strip() removes leading/trailing whitespace (common when cleaning user input), find() returns the index of a substring (or -1), and replace() swaps text.

Visual Explanation

0P-61y-52t-43h-34o-25n-1slice [1:4]
name = "Python": each character has a positive index from the left and a negative index from the right. name[1:4] selects indices 1, 2, 3.
πŸ’‘ Why does this work?

Read the concept explanation above again slowly, line by line β€” every keyword there maps directly onto a line of code in the examples. If it still doesn't click, re-run the traced example (if this lesson has one) one step at a time.

πŸ” What happens internally? (advanced)

Under the hood, Python compiles your source into bytecode and runs it on a virtual machine (the CPython interpreter). Variables are names in a namespace dictionary pointing at objects in memory β€” which is exactly what the memory panel in the tracer above is showing you.

Common Mistakes

βœ— Common mistake 1

input() always returns text. Adding a string and an integer directly raises a TypeError.

βœ— Avoid this
This raises TypeError: can only concatenate str (not "int") to str
age = input("Age: ")
print(age + 5)
βœ“ Better approach
Fixed
age = int(input("Age: "))
print(age + 5)
βœ— Common mistake 2

Strings are <strong>immutable</strong> β€” you cannot change one character in place. Methods like replace() and upper() always return a brand-new string.

βœ— Avoid this
This raises TypeError: 'str' object does not support item assignment
name = "python"
name[0] = "P"
βœ“ Better approach
Fixed
name = "python"
name = "P" + name[1:]
βœ“ Best practices
  • Prefer f-strings over + concatenation β€” they're more readable, especially with several variables.
  • Always convert input() before doing math: int(input(...)) or float(input(...)).
  • Use .strip() on user-typed input to remove accidental leading/trailing spaces.
  • Remember slicing never raises an error for out-of-range indices β€” it just returns as much as it can.

Exercise & Challenge

Exercise 1 β€” Predict the output

Given this code
word = "handbook"
print(word[2:6])

What does this print?

πŸ† Challenge

Ask the user for their first and last name (two separate input() calls) and print a formatted greeting using an f-string, with the name in Title Case.

  • Use two input() calls
  • Combine both names into one f-string
  • Use .title() to fix inconsistent capitalization
πŸ’‘ Need a hint?

"ada LOVELACE".title() becomes "Ada Lovelace".

πŸ” Show a sample solution
Python
first = input("First name: ")
last = input("Last name: ")
full = f"{first} {last}".title()
print(f"Welcome, {full}!")

Quiz

Answer every question, then submit to see your score and explanations.

1. What type does input() always return?

int
str
float
bool
input() always returns a string, no matter what the user types.

2. What is "Python"[-1]?

P
n
y
IndexError
Negative indices count from the end; -1 is the last character, 'n'.

3. What does "Python"[1:4] return?

Pyt
yth
ytho
hon
Slicing [1:4] includes indices 1, 2, 3 β†’ 'yth'.

4. Why does name[0] = "P" raise an error?

Strings can't start with a capital letter
Strings are immutable
0 is not a valid index
Python requires quotes there
Strings can't be modified in place β€” you must build a new string instead.

5. Which method removes leading and trailing whitespace from a string?

trim()
clean()
strip()
remove()
strip() removes whitespace (or specified characters) from both ends.

Summary

  • input() reads text from the user and always returns a string.
  • Convert input with int()/float() before doing arithmetic on it.
  • Strings support indexing ([i]) and slicing ([start:stop:step]); indices start at 0.
  • Strings are immutable β€” methods like replace() return new strings rather than modifying the original.

Related lessons

Saved privately in your browser β€” no account needed.