Text (strings) in Python
Topic 4 of 58 · 9 minFree lessonA string is a piece of text. It can hold letters, spaces, digits and symbols. You make one by putting text inside quotes.
greeting = "Hello"language = 'Python'print(greeting)print(language)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.
print("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.
first = "Ada"last = "Lovelace"print(first + " " + last)Use * to repeat a string.
print("ha" * 3)How long is it?
len() counts the characters in a string. Spaces and punctuation count too.
print(len("Python"))print(len("Hi there!"))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.
word = "Python"print(word[0])print(word[1])Negative numbers count from the end. -1 is always the last character.
word = "Python"print(word[-1])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.
print("Line one\nLine two")+. Python won't guess what you mean, so it stops with a TypeError.print("Age: " + 30)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.