The str type represents Unicode text in Python. Strings are useful for names, messages, file paths, and any other sequence of characters.
Understanding the Concept
Create a string by placing text in single or double quotation marks. Strings can contain letters, digits, spaces, and punctuation, but a string containing digits is still text until converted. You can join strings, get their length, index characters, and call methods such as upper() or strip(). Python strings are immutable: operations that transform text return a new string rather than editing individual characters of an existing one.
When and Why You Would Use This
Try a small greeting built from two string values. The example includes one method call and a length check to show that text is more than something you only print.
Practical Example
first_name = "Alex"
last_name = "Morgan"
full_name = first_name + " " + last_name
print(full_name)
print("Characters:", len(full_name))
Understanding the Example
The output includes Alex Morgan and Characters: 11. The space inserted between names counts as one character. String concatenation joins text, not numbers.
Example Output
Alex Morgan
Characters: 11
Try It Yourself
Create a title from three separate words and display both the title and its length.
Common Beginner Mistakes
- Treating a string of digits as a number without converting it.
- Forgetting to include a space when joining words.
- Trying to change one character in an existing string in place.
Key Takeaways
- str holds Unicode text.
- Strings can be joined, inspected, and transformed with methods.
- String values are immutable.