Strings: Text, Quotes, and Length

Python for Absolute Beginners · Lesson 6

What you’ll learn

1 / 16

What a string is

2 / 16

A string in code

message = "Hello, world!"
print(message)

Output:
Hello, world!

The quotes mark the value as text.

3 / 16

Single quotes or double quotes?

4 / 16

Quotes in code

print('Sam said "Hi!"')
print("It's a sunny day.")

Output:
Sam said "Hi!"
It's a sunny day.

Choose whichever keeps your text intact; there is no other difference.

5 / 16

Joining and repeating strings

6 / 16

Joining strings in code

first = "Hello"
second = "Sam"
print(first + " " + second)

Output:
Hello Sam

Without the " " in the middle, you would get HelloSam.

A string and a number do not join: print("You are " + 9) gives TypeError: can only concatenate str (not "int") to str. Fix it with str(9), or use a comma: print("You are", 9).

7 / 16

Repeating a string in code

print("Ha! " * 3)

Output:
Ha! Ha! Ha!

With text, * means “repeat.”

8 / 16

Length, and reading one character

9 / 16

Length in code

word = "hello world"
print(len(word))

Output:
11

h-e-l-l-o (5), one space (6), w-o-r-l-d (11).

10 / 16

Reading one character in code

word = "Sam"
print(word[0])
print(word[1])
print(word[2])
print(word[len(word) - 1])

Output:
S
a
m
m

word[0] is S, word[1] is a, word[2] is m. The last character is at position len(word) - 1, which prints m. Asking for word[3] gives IndexError: string index out of range.

11 / 16

Putting it together

name = "Mia"
print("Hello, " + name + "! You are learning Python.")

Output:
Hello, Mia! You are learning Python.

Strings, variables, and joining combine into the kind of line real programs use.

12 / 16

Hands-on exercise

13 / 16

Key takeaways

14 / 16

Take the quiz

Take the Lesson 6 quiz — 5 quick questions to check what you learned.

15 / 16

Next lesson

Talking to Your Program: input()

16 / 16

Press play on any slide and the lesson plays on by itself from there. You can still click Next or click a slide to move on.