Legends ofPythos
Claim your name
Python Basics

Working with text

Lesson 4 of 13

Watch the lesson1:00 ยท with Sigrid
Text in Python is called a string. You can wrap strings in single quotes like 'hello' or double quotes like "hello". Both work the same way. A common beginner mistake is opening a string with one kind of quote and closing it with the other, like 'hello", which is an error.

Joining text

first = "Py"
last = "thon"
full = first + last
print(full)
Prints Python
You can join strings using the + operator. This is called concatenation. It sticks one string right next to another without adding spaces automatically.

f-strings

name = "Ada"
message = f"Hello, {name}!"
print(message)
Prints Hello, Ada!
f-strings are the modern way to mix variables and text. Start the string with f, then put variable names inside curly braces {}. Python replaces each brace section with the value of that variable.

Cleaning and changing text

word = "  hello  "
print(len(word))        # 9 - counts the spaces too
print(word.upper())     # "  HELLO  " - everything uppercase
print(word.lower())     # "  hello  " - everything lowercase
print(word.strip())     # "hello" - outer spaces removed
Common string operations
len() counts every character, including hidden spaces. .upper(), .lower(), and .strip() do not change the original variable. They return a new version of the text with changes applied.

Accessing characters

word = "python"
print(len(word))   # 6 - the word is six letters long
print(word[0])     # p - the first character
print(word[-1])    # n - the last character
Indexing starts at zero and can count backwards
Strings are indexed starting from 0. The first letter is index 0, the second is 1, and so on. You can also use negative numbers to start counting from the end, where -1 is the last character.

Your turn

0 of 3 solved

Exercise 1

+25 XP
Create two variables, first_name and last_name, and put any name you like in each one. Use an f-string to build a variable full_name holding the two of them with a single space in between. Print full_name.
Write your Python here.

Run your code to check it against the tests.

Exercise 2

+25 XP
Take the string " hello world ". Remove the extra spaces on both ends, convert it to uppercase, and print the result.
s = " hello world "

Run your code to check it against the tests.

Exercise 3

+25 XP
Create a variable word set to "python". Print the length of the word, and print its first character.
Write your Python here.

Run your code to check it against the tests.