CodeMIRAI
0 XP

Strings

2 min read 8 runnable examples Quiz included

A string is a sequence of characters: letters, digits, spaces, symbols, even emoji. Strings are written in single or double quotes.

Python
greeting = "Hello"
language = 'Python'
print(greeting, language)

Multi-line strings

Triple quotes let a string span several lines; the line breaks are kept:

Python
poem = """Roses are red,
Violets are blue,
Python is readable,
And so are you."""
print(poem)

Joining and repeating

+ joins (concatenates) strings and * repeats them:

Python
first = "Code"
second = "Mirai"
print(first + second)
print(first + " " + second)
print("-" * 20)

Length

len() counts the characters, including spaces:

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

Checking what a string contains

The in operator tests whether one string appears inside another:

Python
sentence = "Python is fun to learn"
print("fun" in sentence)
print("boring" in sentence)
print("python" in sentence)   # case matters!
print("boring" not in sentence)

Strings are immutable

Once created, a string cannot be changed in place. Operations always create a new string:

Python
word = "cat"
word.upper()          # makes "CAT" but we threw it away
print(word)

word = word.upper()   # keep the new string
print(word)

Trying to change a single character fails:

Python
word = "cat"
word[0] = "b"

To change part of a string, build a new one, for example "b" + word[1:], which uses slicing from the next lesson.

Comparing strings

Python
print("apple" == "apple")
print("apple" == "Apple")
print("apple" < "banana")    # alphabetical (dictionary) order
print("Zebra" < "apple")     # capitals come before lower case!

Strings compare character by character using their Unicode codes, and every capital letter has a smaller code than every lower-case letter. To compare without caring about case, compare a.lower() == b.lower().

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.