CodeStride
Getting Started

Text (strings) in Python

Topic 4 of 58 · 9 minFree lesson

A string is a piece of text. It can hold letters, spaces, digits and symbols. You make one by putting text inside quotes.

Example 1
greeting = "Hello"language = 'Python'print(greeting)print(language)
HelloPython

Double quotes and single quotes work the same way. If your text has an apostrophe in it, wrap it in double quotes so Python knows where the string ends.

Example 2
print("It's sunny today.")
It's sunny today.

Joining strings

Use + to join strings together. This is called concatenation. Python won't add spaces for you, so put them in yourself.

Example 3
first = "Ada"last = "Lovelace"print(first + " " + last)
Ada Lovelace

Use * to repeat a string.

Example 4
print("ha" * 3)
hahaha

How long is it?

len() counts the characters in a string. Spaces and punctuation count too.

Example 5
print(len("Python"))print(len("Hi there!"))
69

Picking out one character

Every character has a position number called an index. Counting starts at 0, not 1. Put the index in square brackets to get that character.

Example 6
word = "Python"print(word[0])print(word[1])
Py

Negative numbers count from the end. -1 is always the last character.

Example 7
word = "Python"print(word[-1])
n

New lines

\n inside a string starts a new line. It's two characters in your code, but Python treats it as one line break.

Example 8
print("Line one\nLine two")
Line oneLine two
Common mistakeJoining a string and a number with +. Python won't guess what you mean, so it stops with a TypeError.
Example 9
print("Age: " + 30)
TypeError: can only concatenate str (not "int") to str

For now, use a comma instead: print("Age:", 30). In the next topic you'll learn f-strings, the neatest way to mix text and numbers.

Try it yourself

Run the code in the editor and answer 8 practice questions on text (strings). It's free, you only need an account.