Skip to content
Visual explainer 3h to learn 4 steps

Strings, f-strings, input & print

Build small interactive programs that read input and format output neatly.

By Invicly Tech, , in Python Programming from Zero. About 11 minutes to read.

Topic 3 of 34

In short

Strings are sequences of characters you can index, slice and transform with methods. input() reads a line the user types, and print() with f-strings shows results neatly formatted.

Explained simply

A string is text: a sequence of characters inside quotes. Single and double quotes mean exactly the same thing, so you can use one kind outside and the other inside, like 'She said "hi"'. Triple quotes (three double quotes) let a string run over several lines.

Every character has a position number called an index, starting at 0. You can pick out one character, cut out a piece (a slice), or call methods, which are built-in actions such as upper(), replace() and split(). Strings never change after they are created; every method gives you back a new string.

print() shows output on the screen. input() shows a prompt, waits for the user to type something and press Enter, and returns what they typed. It always returns a string, even when the user types digits, so you convert it before doing maths.

f-strings are the modern way to put values into text. Put an f before the quotes and write any expression inside braces: f"Total: {total}". After a colon inside the braces you can control the look: number of decimals, width, alignment and thousands separators. One small f-string often replaces a lot of messy joining with +.

Press Play on a diagram to walk through it one step at a time.

FlowA tiny interactive program
  1. 1
    input() prompt

    User types text and presses Enter

  2. 2
    Get a str

    input() always returns a string

  3. 3
    Clean & convert

    strip() spaces, then float() or int()

  4. 4
    Compute

    Do the calculation with real numbers

  5. 5
    print(f"...")

    Format the result inside an f-string

CompareIndexing vs slicing "Python"
Indexing s[i]
  • s[0] is "P"
  • s[-1] is "n"
  • Returns one character
  • Out of range raises IndexError
Slicing s[a:b]
  • s[0:2] is "Py"
  • Stop index is excluded
  • s[::-1] reverses: "nohtyP"
  • Out of range is safe
MapString methods by job
str methods
  • Clean
    • strip()
    • lower(), casefold()
    • removeprefix()
  • Split and join
    • split()
    • splitlines()
    • "sep".join(list)
  • Search
    • find(), index()
    • count()
    • startswith(), endswith()
  • Change
    • replace()
    • upper(), title()
  • Test
    • isdigit()
    • isalpha()
    • isspace()
CompareThree ways to put values into text
% formatting
  • "Hi %s" % name
  • Oldest style
  • Still seen in logging
  • Easy to get wrong
str.format()
  • "Hi {}".format(name)
  • Same spec language
  • Good for reusable templates
  • More typing
f-string
  • f"Hi {name}"
  • Python 3.6+
  • Expression right in place
  • Use this by default

In depth

Strings are immutable Unicode text

Each character in a Python string is a Unicode code point, so any language works: len("café") is 4 and len("日本") is 2. ord("A") gives the number 65 and chr(65) gives "A" back.

Strings are immutable. s[0] = "J" raises TypeError. To change text, build a new string, for example "J" + s[1:], or s.replace("old", "new"), and assign the result to a name. When you build a long string from many pieces in a loop, collect the pieces in a list and join them once at the end with "".join(parts). That is the clear, standard way and it stays fast for big inputs.

A backslash starts an escape sequence: \n is a new line, \t a tab and \\ a real backslash. That is a trap with Windows paths, because "C:\new" contains a newline. Use a raw string, r"C:\new", or simply forward slashes, which Python accepts on Windows too.

  • len(s) counts characters, not bytes
  • "ab" * 3 is "ababab"
  • "py" in "python" is True

The string methods you will use every day

Cleaning: strip() removes spaces and newlines from both ends; lstrip() and rstrip() do one side. lower() and upper() change case; casefold() is the stronger version for comparing text in any language.

Splitting and joining: split() with no argument splits on any run of whitespace and drops empty pieces, which is what you want for words. split(",") splits on exactly that character and keeps empty fields, which matters for data. ", ".join(words) glues a list of strings back together.

Searching: find(x) returns the index of x or -1 if it is missing; index(x) does the same but raises ValueError. count(x) counts non-overlapping matches. startswith() and endswith() accept a tuple, so name.endswith((".jpg", ".png")) checks both. removeprefix() and removesuffix() (Python 3.9+) remove an exact piece only if it is there.

Testing: isdigit(), isalpha() and isspace() return True or False for the whole string.

Comparesplit() vs split(" ") on " a b "
split()
  • Splits on any run of whitespace
  • Ignores spaces at the ends
  • Result: ['a', 'b']
  • Best for words
split(" ")
  • Splits on every single space
  • Keeps empty pieces
  • Result: ['', 'a', '', 'b', '']
  • Use split(",") style for data

f-string format specs, decoded

Inside the braces of an f-string you write {value:spec}. The spec is a tiny language read from left to right. An optional fill character and an alignment sign come first: < left, > right, ^ center. Then a width, the minimum number of characters. Then a comma for thousands separators. Then a precision such as .2 and a type letter: f for fixed decimals, % for percent, e for scientific notation, d for whole numbers.

So f"{1234.5:>10,.2f}" gives " 1,234.50": right-aligned in 10 characters, with a comma and two decimals. f"{7:03}" gives "007" and f"{0.256:.1%}" gives "25.6%".

Two extras are very handy. f"{x=}" prints both the expression and its value, like x=5, which is perfect for quick debugging. !r shows a value's repr, so f"{name!r}" prints quotes and makes hidden spaces visible. From Python 3.12 you can reuse the same quote type inside the braces; on older versions use the other kind.

FlowReading the spec in f"{price:>10,.2f}"
  1. 1
    price

    The expression to show

  2. 2
    >

    Align right

  3. 3
    10

    Use at least 10 characters

  4. 4
    ,

    Add thousands separators

  5. 5
    .2f

    Fixed point with 2 decimals

print() and input() in more detail

print() takes any number of values and turns each into text. sep sets what goes between them (a space by default) and end sets what goes after the last one (a newline by default). print("a", "b", sep="-") shows a-b, and print("Loading", end="") keeps the cursor on the same line. flush=True forces the text out immediately, which helps before a slow step.

input(prompt) prints the prompt, waits for Enter, removes the final newline and returns the rest as a str. If the input ends without a line, for example the user presses Ctrl+D or the program reads from an empty file, it raises EOFError. Ctrl+C raises KeyboardInterrupt.

Users type surprising things: spaces, empty lines, "twelve". Strip the text, check for the empty case, and wrap int() or float() in try/except ValueError inside a loop that asks again. A program that survives silly input feels professional.

SequenceOne round of input() and print()
Your code
input()
User
  1. 1input("Age: ")
    Your code to input(): input("Age: ")
  2. 2Shows Age: and waits
    input() to User: Shows Age: and waits
  3. 3Types " 42" and presses Enter
    User to input(): Types " 42" and presses Enter
  4. 4Returns " 42" as a str
    input() to Your code: Returns " 42" as a str
  5. 5int(" 42") gives 42
    Your code to Your code: int(" 42") gives 42
  6. 6print(f"Next year: {age + 1}")
    Your code to User: print(f"Next year: {age + 1}")

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Index, slice and call string methods~45m
  2. 2
    Format output with f-strings~45m
  3. 3
    Read user input with input()~45m
  4. 4
    Build a small interactive calculator~45m

Key points

  • Strings are immutable: methods like upper() return a new string.
  • Indexes start at 0; negative indexes count from the end.
  • f-strings embed expressions: f"{total:.2f}" shows two decimal places.
  • input() always returns a str, so convert it before doing maths.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
word = "Python"
print(word[0], word[-1], word[1:4])  # P n yth
print(word.upper(), word.lower())

a = float(input("First number: "))
b = float(input("Second number: "))
op = input("Operator (+ - * /): ").strip()

if op == "+":
    result = a + b
elif op == "-":
    result = a - b
else:
    result = a * b if op == "*" else a / b
print(f"{a} {op} {b} = {result:.2f}")

A minimal calculator: read, convert, compute, format.

Printing a receipt with aligned columns

You want a tidy receipt instead of ragged text. Step 1: print a header using the same widths you will use for the rows. Step 2: for each item, compute the line total. Step 3: print the name left-aligned in 14 characters, the quantity right-aligned in 4 and the money right-aligned in 9 with two decimals. Step 4: print a separator with "-" * 27 and the grand total. Because every row uses the same specs, the columns line up perfectly.

python
items = [("Coffee", 2, 3.5), ("Bagel", 1, 2.25), ("Orange juice", 3, 4.0)]

print(f"{'Item':<14}{'Qty':>4}{'Total':>9}")
total = 0
for name, qty, price in items:
    line = qty * price
    total += line
    print(f"{name:<14}{qty:>4}{line:>9.2f}")
print("-" * 27)
print(f"{'TOTAL':<18}{total:>9.2f}")
# Coffee           2     7.00
# ...
# TOTAL                 21.25

Cleaning up a name the user typed

Users type " aDa lovelace " with odd spaces and casing. Step 1: split() breaks the text on any run of whitespace and drops the ends. Step 2: " ".join() puts the words back with single spaces. Step 3: title() fixes the casing. Step 4: split(" ", 1) splits once into first and last name. Step 5: take the first letter of each for initials. Note that a single-word name would make step 4 fail, so real code should check len(parts) first.

python
raw = input("Full name: ")             # "  aDa   lovelace "
name = " ".join(raw.split()).title()    # "Ada Lovelace"
first, last = name.split(" ", 1)
initials = first[0] + last[0]

print(f"Hello, {first}! Your initials are {initials}.")
print(f"{raw!r} became {name!r}")

Quick reference

  • s.strip() trims spaces and newlines at both ends; s.split() splits on any run of whitespace
  • ", ".join(words) glues a list of strings with ", " between them
  • s.find(x) returns -1 if x is missing; s.index(x) raises ValueError instead
  • f"{n:,}" adds thousands separators; f"{x:.1%}" shows 0.256 as 25.6%
  • f"{name:<10}" pads to 10 characters left-aligned; > aligns right and ^ centers
  • f"{x=}" prints x=5, handy for quick debugging (Python 3.8+)
  • print(a, b, sep=", ", end="") changes the separator and the line ending
  • Raw strings like r"C:\new" keep backslashes as typed (Windows paths, regex)

Common mistakes

  • Forgetting that input() returns text, so "2" + "3" gives "23".
  • Expecting s.upper() to change s in place; strings never change.
  • Forgetting the f prefix, so {name} prints literally.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What does "banana".find("x") return?

Question 2

2What is "a,,b".split(",")?

Question 3

3What does f"{3.14159:.2f}" produce?

Question 4

4The user types 5 at x = input(). What is x * 2?

Question 5

5s = "hello". What happens when you run s[0] = "H"?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Given s = " Hello, World ", print it stripped, then in lower case, then with the comma removed, and finally print how many letters o it contains.

  2. Exercise 2medium

    Ask for some text and print whether it is a palindrome, ignoring case and spaces. "Never odd or even" should count as one.

  3. Exercise 3hard

    Build a calculator loop. It reads lines like 12 * 3.5, prints the result rounded to 4 decimals, survives bad numbers, unknown operators and division by zero, and stops when the user types q.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Should I use single or double quotes in Python?
They are identical. Pick one style for the project (the Black and Ruff formatters use double quotes) and switch only when it saves escaping, as in 'She said "hi"'.
How do I print without a new line?
Pass end="", as in print("Loading", end=""). Add flush=True if the text must appear immediately, for example before a slow step.
Why use f-strings instead of joining with +?
f-strings convert values to text for you, so you avoid TypeError from mixing str and int, and they format numbers in the same place. They are also easier to read.
How do I read a number safely with input()?
Call int() or float() inside try/except ValueError, in a loop that asks again until the conversion works. Strip the text first so checks like == "q" are not fooled by spaces.

Go deeper

ShareXLinkedInWhatsApp