Strings
In programming, we don't call text "text" or "words" - we call it a String.
A String is simply a sequence of characters (letters, numbers, or symbols) strung together. In Python, you tell the computer that something is a String by wrapping it in quotation marks.
1. Three Ways to Create Strings
You can create strings in Python using single quotes, double quotes, or triple quotes for multi-line paragraphs:
# 1. Single quotes
first = 'Python'
# 2. Double quotes
second = "Python"
# 3. Triple quotes for multiple lines
paragraph = """This is
a multi-line
text paragraph."""
:::tip Apostrophes inside text
Use double quotes when your text contains apostrophes so Python does not get confused by the single quote inside: "It's Python time!"
:::
2. Combining Strings
You can join strings together using the + operator (called concatenation), or repeat them using *:
first_name = "Ravi"
last_name = "Kumar"
# Join two strings with a space in the middle
full_name = first_name + " " + last_name
print(full_name) # Output: Ravi Kumar
# Repeat a string 5 times
stars = "*" * 5
print(stars) # Output: *****
3. String Length
Use len() to count how many total characters (including spaces and punctuation) are inside a string:
message = "Hello"
print(len(message)) # Output: 5
empty_string = ""
print(len(empty_string)) # Output: 0
4. Converting Numbers to Strings
If you want to join text with numbers, you must first convert the number into a string using str():
age = 25
message = "I am " + str(age) + " years old"
print(message) # Output: I am 25 years old
Tip: Adding strings together using
+andstr()can get messy if you have a lot of variables. In the next module (Input & Output), we will learn a much cleaner way to build sentences called f-strings!
5. Common Mistakes to Avoid
Mistake 1: Mismatched Quotes
Always match your opening and closing quotes.
# Wrong - opening with double quote and closing with single quote
text = "Hello'
# Right - matching quotes on both sides
text = "Hello"
text = 'Hello'
Mistake 2: Adding Strings and Numbers Directly
Python cannot add raw numbers and text together directly.
# Wrong - raises TypeError
result = "Age: " + 25
# Right - convert the number first using str()
result = "Age: " + str(25)
Mistake 3: Forgetting Quotes Around Words
Without quotes, Python thinks a word is a variable name.
# Wrong - Python searches for a variable named Kavya
name = Kavya
# Right - quotes tell Python this is text
name = "Kavya"