Python Strings
Strings allow us to work with text, such as names, sentences, or any sequence of characters. You’ll learn how to create and manipulate strings, use built-in string methods, and explore string formatting.
Table of Contents
What is a String?
A string is a sequence of characters enclosed in either single quotes ('
) or double quotes ("
). Both single and double quotes are valid in Python, and you can use them interchangeably.
Creating Strings:
# Using single quotes
message = 'Hello, world!'
# Using double quotes
greeting = "Hi there!"
# Strings can also be empty
empty_string = ''
Multiline Strings:
If you need a string that spans multiple lines, you can use triple quotes ('''
or """
).
multiline_message = """This is a string
that spans
multiple lines."""
Accessing Characters in Strings
Strings are indexed, meaning each character in a string has a position, starting from 0 for the first character. You can access individual characters by using square brackets ([]
).
Example:
word = "Python"
print(word[0]) # Output: 'P'
print(word[3]) # Output: 'h'
You can also use negative indexing to access characters from the end of the string.
print(word[-1]) # Output: 'n' (last character)
print(word[-2]) # Output: 'o'
String Slicing
You can extract a part of a string (known as a substring) by slicing it. The slice syntax is string[start:end]
, where start
is the index where the slice begins, and end
is where the slice ends (but the character at the end
index is not included).
Examples:
word = "Python"
print(word[0:3]) # Output: 'Pyt' (characters from index 0 to 2)
print(word[2:5]) # Output: 'tho' (characters from index 2 to 4)
If you leave out start
or end
, Python assumes you want the slice to start from the beginning or go to the end of the string:
print(word[:3]) # Output: 'Pyt' (first three characters)
print(word[3:]) # Output: 'hon' (characters from index 3 to the end)
String Concatenation and Repetition
You can concatenate (join) two or more strings using the +
operator. You can also repeat a string using the *
operator.
Examples:
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name) # Output: 'John Doe'
# Repeating a string
laugh = "ha" * 3
print(laugh) # Output: 'hahaha'
Common String Methods
Python provides a whole bunch of built-in methods to manipulate strings. Here are some of the most useful ones:
Method | Description | Example |
---|---|---|
upper() | Converts the string to uppercase | 'hello'.upper() → 'HELLO' |
lower() | Converts the string to lowercase | 'HELLO'.lower() → 'hello' |
strip() | Removes leading and trailing whitespace | ' hello '.strip() → 'hello' |
replace(old, new) | Replaces all occurrences of a substring with another | 'hello'.replace('e', 'a') → 'hallo' |
split(separator) | Splits a string into a list based on the separator | 'a,b,c'.split(',') → ['a', 'b', 'c'] |
join(list) | Joins elements of a list into a string with a separator | ','.join(['a', 'b', 'c']) → 'a,b,c' |
find(substring) | Finds the index of the first occurrence of a substring | 'hello'.find('e') → 1 |
Examples:
message = " Hello, World! "
# Convert to uppercase
print(message.upper()) # Output: ' HELLO, WORLD! '
# Remove spaces
print(message.strip()) # Output: 'Hello, World!'
# Replace characters
print(message.replace("World", "Python")) # Output: ' Hello, Python! '
# Split into a list of words
print(message.split()) # Output: ['Hello,', 'World!']
String Immutability
In Python, strings are immutable, meaning you cannot change a string after it has been created. If you want to modify a string, you need to create a new one.
Example:
word = "Hello"
# This will raise an error because strings are immutable
# word[0] = "h"
# You can create a new string
new_word = "h" + word[1:] # 'h' + 'ello'
print(new_word) # Output: 'hello'
String Formatting
Python provides several ways to format strings and insert variables into them.
1. Concatenation with “+”:
This is the simplest way, but it can get messy with too many variables.
name = "Alice"
age = 30
print("My name is " + name + " and I am " + str(age) + " years old.")
2. Formatting with f-Strings:
F-strings are the most modern and recommended way to format strings in Python. Introduced in Python 3.6, they allow you to embed expressions inside curly braces {}
.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")
3. Using the Format() Method:
The format()
method allows you to insert values into placeholders ({}
) in the string.
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age))
4. Percent (%) Formatting:
An older way of formatting strings, using %
placeholders, is still supported but less preferred than f-strings
.
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age))
Escape Characters
Sometimes you need to include special characters in your strings, like quotes, newlines, or tabs. Python uses escape characters (backslash \
) to include special characters in strings.
Escape Sequence | Description | Example |
---|---|---|
\' | Single quote | 'It\'s sunny' |
\" | Double quote | "He said, \"Hi!\"" |
\\ | Backslash | 'C:\\path\\folder' |
\n | Newline | 'Hello\nWorld' |
\t | Tab | 'Hello\tWorld' |
Examples:
print("It\'s a beautiful day!") # Output: It's a beautiful day!
print("Hello\nWorld") # Output: Hello (new line) World
Key Concepts Recap
- Strings are sequences of characters enclosed in quotes, and they are immutable.
- You can access individual characters using indexing and extract parts of strings using slicing.
- Use string methods to modify or analyze strings, such as
.upper()
,.strip()
,.replace()
, and.split()
. - Strings can be concatenated using
+
and repeated using*
. - String formatting can be done using f-strings, the
format()
method, or the%
operator. - Escape characters let you include special characters like quotes or newlines in strings.
Exercises
- Write a program that asks the user for their first name and last name, then prints a greeting using both names.
- Create a string variable that contains a sentence. Use string methods to:
- Convert the sentence to uppercase.
- Replace a word in the sentence.
- Split the sentence into individual words.
- Write a program that asks the user for a word, then prints the word in reverse order using string slicing.
- Experiment with formatting a sentence that includes a person’s name, age, and favorite color using both
f-strings
and theformat()
method.
Next time, we’ll introduce control flow and start learning how to use if statements to make decisions in your Python programs.
FAQ
Q1: What’s the difference between single quotes ('
) and double quotes ("
) in Python strings?
A1: In Python, there is no functional difference between single quotes ('
) and double quotes ("
). You can use either to create strings, and it’s purely a matter of preference. However, using one type allows you to include the other inside your string without needing to escape it. For example:
name = "It's a nice day" # Double quotes allow single quote inside
quote = 'He said, "Hello!"' # Single quotes allow double quotes inside
Q2: Why am I getting an error when I try to change a character in a string?
A2: Strings in Python are immutable, meaning you cannot modify them after they are created. If you try to change a character directly (e.g., my_string[0] = "h"
), you’ll get an error. To change a string, you need to create a new one by modifying it and assigning it to a new variable or replacing the old one:
word = "Hello"
new_word = "h" + word[1:] # Output: "hello"
Q3: How do I include both single and double quotes inside a string?
A3: You can use escape characters to include both types of quotes inside a string. The backslash (\
) is used to escape quotes:
sentence = 'She said, "It\'s a beautiful day!"'
print(sentence) # Output: She said, "It's a beautiful day!"
Alternatively, you can use triple quotes ('''
or """
) to avoid needing escape characters:
sentence = """She said, "It's a beautiful day!" """
Q4: What’s the difference between split()
and join()
in Python?
A4: The split()
method is used to break a string into a list of substrings based on a delimiter, while join()
does the opposite — it joins a list of strings into a single string with a specified separator.
split()
example:
text = "apple,banana,orange"
fruits = text.split(",")
print(fruits) # Output: ['apple', 'banana', 'orange']
join()
example:
fruits = ['apple', 'banana', 'orange']
result = ", ".join(fruits)
print(result) # Output: "apple, banana, orange"
Q5: How do I reverse a string in Python?
A5: You can reverse a string in Python using slicing. The slice [::-1]
returns the string with its characters in reverse order:
word = "Python"
reversed_word = word[::-1]
print(reversed_word) # Output: "nohtyP"
Q6: Why does Python return a list when I use the split()
method?
A6: The split()
method breaks a string into a list of substrings based on a specified delimiter (which is a space by default). This is useful when you want to process or analyze different parts of a string. For example:
sentence = "Hello world"
words = sentence.split() # Split by spaces
print(words) # Output: ['Hello', 'world']
If you want the entire string as a single element in the list, you can specify an empty string as the delimiter (split('')
), but this usually isn’t needed unless you want to separate each character.
Q7: What’s the difference between strip()
, lstrip()
, and rstrip()
?
A7: These methods are used to remove whitespace (or other specified characters) from strings:
strip()
removes whitespace from both ends of the string:
text = " Hello "
print(text.strip()) # Output: "Hello"
lstrip()
removes whitespace from the left (beginning) of the string:
text = " Hello "
print(text.lstrip()) # Output: "Hello "
rstrip()
removes whitespace from the right (end) of the string:
text = " Hello "
print(text.rstrip()) # Output: " Hello"
Q8: How can I check if a substring exists within a string?
A8: You can use the in
operator to check if a substring exists in a string. This will return True
if the substring is found, and False
if it isn’t:
sentence = "Python is fun"
print("Python" in sentence) # Output: True
print("Java" in sentence) # Output: False
Q9: What are f-strings, and why should I use them?
A9: F-strings (formatted string literals) allow you to easily embed expressions inside string literals by prefixing the string with an f
or F
and using curly braces {}
to insert variables or expressions. They are more readable and efficient than older methods like format()
or %
formatting.
Example:
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.") # Output: My name is Alice and I am 30 years old.
F-strings are the preferred method for string formatting in modern Python (Python 3.6 and above).
Q10: How do I format numbers inside a string using f-strings?
A10: F-strings allow you to format numbers inside the string using special formatting options. You can specify things like decimal places, padding, or alignment:
pi = 3.14159
print(f"Pi rounded to two decimal places: {pi:.2f}") # Output: Pi rounded to two decimal places: 3.14
In this example, .2f
ensures that the value is displayed with two decimal places. F-strings provide great flexibility for formatting numbers and dates.
Q11: Can I use variables and expressions inside f-strings?
A11: Yes, you can include both variables and expressions inside f-strings. Python will evaluate the expressions and insert the result into the string:
a = 5
b = 10
print(f"The sum of {a} and {b} is {a + b}.") # Output: The sum of 5 and 10 is 15.
This makes f-strings a powerful and concise way to build strings with dynamic content.
Q12: How do I replace all occurrences of a word in a string?
A12: You can use the replace()
method to replace all occurrences of a substring within a string:
sentence = "Python is great. Python is fun."
new_sentence = sentence.replace("Python", "Java")
print(new_sentence) # Output: Java is great. Java is fun.
The replace()
method replaces every occurrence of the specified substring. You can also limit the number of replacements by providing an additional argument.
Q13: Why is the find()
method returning -1
?
A13: The find()
method searches for a substring in a string and returns the index of its first occurrence. If the substring is not found, it returns -1
. For example:
sentence = "Hello, world!"
index = sentence.find("world") # Output: 7 (index of 'world')
index = sentence.find("Python") # Output: -1 (because 'Python' is not in the string)
If -1
is returned, it means the substring is not present in the string.
Q14: Why does Python allow both positive and negative string indexes?
A14: Python allows both positive and negative indexing to give you flexibility when working with strings. Positive indexes count from the beginning of the string (starting at 0), while negative indexes count from the end of the string (starting at -1). This makes it easier to work with strings without needing to know their exact length.
Example:
word = "Python"
print(word[0]) # Output: 'P' (first character)
print(word[-1]) # Output: 'n' (last character)
Negative indexing is particularly useful when you want to access characters relative to the end of the string.