A string is text: a name, a message, a password, a line from a file. Python has dozens of built-in tools for working with text. These are the ones you will use all the time.
INDEXING: ONE CHARACTER
word = "python"
print(word[0])
print(word[-1])
print(len(word))p
n
6
Counting starts at 0. Negative numbers count from the end, so [-1] is the last character.
SLICING: A PIECE OF THE TEXT
word = "snekcade"
print(word[0:4])
print(word[4:])
print(word[::-1])snek
cade
edackens
[start:stop] takes characters from start up to, but not including, stop. [::-1] walks backwards and reverses the string.
THE MOST USEFUL STRING METHODS
msg = " Hello, Snek! "
print(msg.strip())
print(msg.lower().strip())
print(msg.replace("Snek", "World").strip())
print("snek" in msg.lower())Hello, Snek!
hello, snek!
Hello, World!
True
strip()removes spaces at the start and end.lower()andupper()change the case.replace(old, new)swaps text.inchecks if one piece of text is inside another.
SPLIT AND JOIN
line = "apple,chips,cookie"
items = line.split(",")
print(items)
print(" + ".join(items))['apple', 'chips', 'cookie']
apple + chips + cookie
split cuts a string into a list. join glues a list back into one string, with your chosen text in between.
STRINGS NEVER CHANGE IN PLACE
name = "snek"
name.upper()
print(name)
name = name.upper()
print(name)snek
SNEK
name = name.upper().F-STRINGS FOR NEAT OUTPUT
player = "Ana"
score = 7
print(f"{player} has {score:03d} points")
print(f"{player:>6}|")Ana has 007 points
Ana|
s = "banana"
print(s.count("a") + s.find("n"))count("a") is 3 and find("n") gives the first position of n, which is 2. 3 + 2 = 5.COMMON BEGINNER MISTAKES
word.upper() to change word. Assign the result back.[-1] for the last character."Level " + 3 fails. Use f"Level {3}" or str(3).PRACTICE IT, DON'T JUST READ IT
Print Plains in Snekcade starts with text and print(): quick puzzles where you guess the output, then write real code. It is free.
PLAY PRINT PLAINS ▸FAQ
How do I reverse a string in Python?
Use slicing with a step of -1: word[::-1].
Why does upper() not change my string?
Strings cannot be changed in place. upper() returns a new string, so store it: name = name.upper().
How do I split a string into words?
Use text.split(). With no argument it splits on spaces; text.split(",") splits on commas.