Beginner âĸ Python
Strings
đ Joining Strings Together
A string is a piece of text inside quotation marks. We can join two strings together using the + sign. Joining strings is called concatenation, which is a fancy word for sticking them end to end. Remember to add a space yourself if you want one between the words!
first = "Super"
second = "Hero"
print(first + second)
print(first + " " + second)SuperHero Super Hero
đ Everything in Strings
Learn how to join text together, build messages with f-strings, measure and change text, and pick out letters and pieces of a string. Here is every step in this topic in one place, so you can review what you learned or jump straight to a step.
đ Joining Strings Together
A string is a piece of text inside quotation marks. We can join two strings together using the + sign. Joining strings is called concatenation, which is a fancy word for sticking them end to end. Remember to add a space yourself if you want one between the words!
first = "Super" second = "Hero" print(first + second) print(first + " " + second)⨠Building Messages with f-strings
An f-string is a string with the letter f in front of it. Inside an f-string, you can put a variable inside curly brackets { } and Python will swap in its value. This makes it easy to build messages that mix text and numbers. You can even do small calculations inside the curly brackets.
name = "Mia" age = 10 print(f"My name is {name} and I am {age} years old.") print(f"Next year I will be {age + 1}.")đ Counting Letters with len()
The len() function tells us how long a string is. It counts every character, which means letters, numbers, symbols, and even spaces. This is useful when you want to check if a password or name is long enough.
word = "Python" print(len(word)) sentence = "I love cats" print(len(sentence))đ Changing Case with upper() and lower()
Strings have special tools called methods that you use with a dot. The upper() method makes every letter a capital letter, and lower() makes every letter small. The original string does not change unless you save the new one in a variable.
animal = "Tiger" print(animal.upper()) print(animal.lower()) print(animal)âī¸ Indexing and Slicing
Every character in a string has a position number called an index. Python starts counting at 0, so the first letter is at index 0. You can use -1 to get the last letter. Slicing with [start:end] gives you a piece of the string, from start up to (but not including) end.
word = "RAINBOW" print(word[0]) print(word[3]) print(word[-1]) print(word[0:4]) print(word[4:])đ Replacing and Searching Text
The replace() method swaps one piece of text for another. The word in lets you check whether some text is inside a string, and it gives back True or False. These tools help you search and fix text in your programs.
message = "I like apples" print(message.replace("apples", "bananas")) print("like" in message) print("pizza" in message)
