Strings
Working with text in Python
In Python, strings are fundamental for handling text. They allow us to store names, messages, and any other sequence of characters.
What are strings?
Think of a string as a series of characters, like letters, numbers, or symbols, all joined together in a specific order. We use them for pretty much anything that involves words or text.
In Python, strings are a type of data, just like numbers. They have their own special ways of working.
Creating strings
You create a string by putting characters inside quotation marks. You can use either single quotes (') or double quotes ("). Python treats them the same.
name = "Alice"
message = 'Hello world!'
print(name)
print(message)Combining strings
You can stick strings together, a process called concatenation, using the + operator. It's like adding them up, but for text.
greeting = "Hi" + " " + "there!"
name = "Bob"
full_message = greeting + " My name is " + name + "."
print(full_message)String length
Sometimes you need to know how many characters are in a string. The built-in len() function does just that.
word = "Python"
count = len(word)
print(count)
sentence = "This is a sentence."
print(len(sentence))Converting to string
What if you have a number but you need it as text? You can convert other data types into strings using the str() function.
age = 30
age_as_string = str(age)
print(type(age))
print(type(age_as_string))
# Now you can combine it with other strings
message = "My age is " + age_as_string + "."
print(message)Common mistakes
Here are a couple of things beginners often run into:
- Forgetting to close quotes: Every opening quote needs a closing one.
- Trying to combine numbers and strings directly: Remember to use
str()to convert numbers first if you're using+.
# This causes an error!
# print("Hello " + 5)
# Do this instead:
print("Hello " + str(5))Practice
Try these exercises to lock in what you just learned.
1word = "PYTHON"2
What's next?
Now that you understand the basics of strings, you're ready to start building simple text-based programs. Next, we'll look at how to get input from a user, which often involves working with strings.