livepython.net
CHAPTER 05Working With Data Types
5.1  STRINGS

Python Strings for Beginners: Join, Repeat and f-strings

What Is a String?

You've used strings since chapter 2. Now let's look at them properly. A string (str) is a sequence of characters inside quotes: letters, digits, spaces and symbols.

Think of a string as a necklace of beads. Each character is one bead, in a fixed order. "Hi!" is three beads: H, i and !.

PYTHONedit me
greeting = "Hello, Sunny!"
print(greeting)
print(type(greeting))
OUTPUT
Hello, Sunny!
<class 'str'>

What you already know

  • Single or double quotes both work; start and end with the same one.
  • Triple quotes let a string go over several lines.
  • Escape sequences like \n and \t work inside any string.

Everything in quotes is text

Digits in quotes are text too, so Python won't do maths with them:

PYTHONedit me
age_text = "25"
age_number = 25
print(type(age_text), type(age_number))
OUTPUT
<class 'str'> <class 'int'>

The empty string

A string can have zero characters: "". It's still a string, just an empty one. You'll use it as a starting value, like an empty box waiting to be filled.

PYTHONedit me
nickname = ""
print("Nickname:", nickname, "(none yet)")
OUTPUT
Nickname:  (none yet)

Notice the two spaces in the output: one before the empty string and one after it.

A string is a necklace of characters inside quotes, even digits and spaces.

your turnPick the right idea

Which of these is a string?

Think about it, then pick one.

Joining and Repeating Strings

You can join strings with the + sign. This is called concatenation (a fancy word for "joining"):

PYTHONedit me
first = "Live"
second = "Python"
print(first + second)
print(first + " " + second)
OUTPUT
LivePython
Live Python
  • + glues strings together exactly as they are.
  • It does not add a space. If you want one, add it yourself: " ".

Repeat with *

* repeats a string a number of times:

PYTHONedit me
print("Ha" * 3)
print("-" * 20)
OUTPUT
HaHaHa
--------------------

You used this trick for lines of stars in chapter 2. Now you know how it works: a string times a whole number.

+ with a comma vs + with a plus

CodeOutputWhy
print("Hi", "Sunny")Hi Sunnyprint() adds a space between items
print("Hi" + "Sunny")HiSunny+ makes one string, no space

You can't add text and a number

PYTHONedit me
age = 25
print("Sunny is " + age)
OUTPUT
TypeError: can only concatenate str (not "int") to str

Don't be scared of this error! It just says: "I can only join text with text." You'll learn two easy fixes in this chapter: f-strings in two lessons, and str() in the last topic.

  • glues strings together, * repeats them. Neither adds spaces.
your turnPredict the output

What will this print?

print("Ha" * 3)
Your turn! What will this code show on the screen?
your turnFill the gap

Fill the gap

first = "Live" second = "Python" print(first ? second)

It should print: LivePython

Which piece makes this code work?

Counting Characters with len()

Want to know how long a string is? The built-in len() function counts its characters:

PYTHONedit me
name = "Sunny"
print(len(name))
print(len("Hello World"))
OUTPUT
5
11

len is short for length. It counts every character: letters, digits, symbols, and spaces too. That's why "Hello World" is 11, not 10.

Characters you can't see still count

PYTHONedit me
print(len(" Hi "))
print(len(""))
print(len("a\nb"))
OUTPUT
4
0
3
  • " Hi " has a space before and after: 4 characters.
  • The empty string "" has 0.
  • "a\nb" has 3: the escape sequence \n is one character, the new line.

Where it's useful

  • Checking that a password is long enough (you'll do that with if in chapter 8).
  • Making a line exactly as long as a title:
PYTHONedit me
title = "LivePython"
print(title)
print("=" * len(title))
OUTPUT
LivePython
==========

Change the title, and the line below it changes length to match. That's variables and len() working together.

Common beginner doubt: "Does len(25) work?" No. Numbers don't have a length, so Python gives a TypeError. len() is for strings (and, later, for lists).

len() counts every character in a string, including spaces.

your turnType the output

Type what this prints

print(len("Hi Sunny"))
Read the code line by line, then type the output exactly.

Building Messages with f-strings

An f-string is the easiest way to put values inside text. Write an f right before the opening quote, and put variables in curly brackets { }:

PYTHONedit me
name = "Sunny"
age = 25
print(f"{name} is {age} years old.")
OUTPUT
Sunny is 25 years old.

Python replaces {name} and {age} with their values. Numbers work too: no TypeError, no +, no worrying about spaces.

Think of it like a form letter: "Dear ____" with a blank that Python fills in for you.

Calculations inside { }

You can put a small calculation in the brackets:

PYTHONedit me
price = 20
qty = 3
print(f"{qty} pens cost {price * qty} rupees.")
OUTPUT
3 pens cost 60 rupees.

Two decimal places

For money, add :.2f after the value to show exactly two decimal places:

PYTHONedit me
total = 4.5
print(f"Total: ${total:.2f}")
OUTPUT
Total: $4.50

Read :.2f as "show as a float with 2 digits after the point".

Don't forget the f

PYTHONedit me
name = "Sunny"
print("Hello, {name}!")
OUTPUT
Hello, {name}!

Without the f, the brackets are just text. It's one of the most common beginner mistakes.

Put an f before the quotes and {variables} inside: Python fills in the values.

your turnPredict the output

What will this print?

city = "Pune" print(f"I live in {city}")
Your turn! What will this code show on the screen?
your turnFix the code

Make it print: Hello, Rocky!

It should print: Hello, Rocky!

name = "Rocky"
print("Hello, {name}!")
This code does not work yet. Fix it, then press Run.
your turnPredict the output

What will this print?

x = 7 x = x + 3 print(x)
Your turn! What will this code show on the screen?

Practice: Strings

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 35.Python Program to Join a First and Last NameEasySolve
  2. 36.Python Program to Count the Characters in a WordEasySolve
  3. 23.Python Program to Calculate and Format a Total CostMediumSolve