Text: Strings

What is a string?

A string is a piece of text: a letter, a word, a sentence, even an empty bit of text. Strings go inside quotes. Single ' ' and double " " quotes both work:

first = "Hello"
second = 'World'
print(first)
print(second)

Output

Hello
World

Use double quotes when your text contains an apostrophe:

print("It's a sunny day")

Output

It's a sunny day

Joining strings

Use + to join (or concatenate) strings:

first_name = "Rahul"
last_name = "Sharma"
full_name = first_name + " " + last_name
print(full_name)

Output

Rahul Sharma

We added " " in the middle, otherwise we'd get RahulSharma.

Repeating strings

Use * to repeat a string:

print("ha" * 3)
print("-" * 20)

Output

hahaha
--------------------

Numbers inside quotes are text

print(5 + 5)
print("5" + "5")

Output

10
55

5 + 5 adds two numbers. "5" + "5" joins two pieces of text, so you get 55.

How long is a string?

len() counts the characters, including spaces:

print(len("Python is fun"))

Output

13
HOME LEARN COMMUNITY DASHBOARD