In this tutorial, you'll learn about Python strings and their basic operations with examples, explanations, and beginner-friendly exercises.
Introduction to Python Strings
A string is a sequence of characters. In Python, anything enclosed in quotes is considered a string. You can use either single ('
) or double ("
) quotes:
message = 'This is a string in Python'
message = "This is also a string"
Handling Quotes Inside Strings
If the string contains a single quote, wrap it in double quotes:
message = "It's a string"
If the string contains double quotes, wrap it in single quotes:
message = '"Beautiful is better than ugly.". Said Tim Peters'
Escaping Characters
Use the backslash (\
) to escape characters:
message = 'It\'s also a valid string'
Raw Strings
Use raw strings to treat backslashes as literal characters:
message = r'C:\python\bin'
Creating Multiline Strings
Use triple quotes ('''
or """
) to define strings that span multiple lines:
help_message = '''
Usage: mysql command
-h hostname
-d database name
-u username
-p password
'''
print(help_message)
Output:
Usage: mysql command
-h hostname
-d database name
-u username
-p password
Using Variables in Strings (f-strings)
Use f-strings to embed variables in string literals. Introduced in Python 3.6:
name = 'John'
message = f'Hi {name}'
print(message)
Output:
Hi John
Concatenating Strings
Literal Concatenation:
greeting = 'Good ' 'Morning!'
print(greeting)
Variable Concatenation:
greeting = 'Good '
time = 'Afternoon'
message = greeting + time + '!'
print(message)
Output:
Good Afternoon!
Accessing Characters in a String
Strings are sequences, so you can use indexing:
text = "Python String"
print(text[0]) # P
print(text[1]) # y
Negative Indexing
print(text[-1]) # g
print(text[-2]) # n
Index Diagram
+---+---+---+---+---+---+---+---+---+---+---+---+---+
| P | y | t | h | o | n | | S | t | r | i | n | g |
+---+---+---+---+---+---+---+---+---+---+---+---+---+
0 1 2 3 4 5 6 7 8 9 10 11 12
-13 -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
Getting the Length of a String
Use len()
to get the number of characters:
text = "Python String"
length = len(text)
print(length)
Output:
13
Slicing Strings
Use slicing to extract substrings:
text = "Python String"
print(text[0:2])
Output:
Py
Syntax:
string[start:end]
-
Includes character at
start
-
Excludes character at
end
-
Omitting
start
= from beginning -
Omitting
end
= to end
Strings Are Immutable
Python strings cannot be changed in-place. Trying to do so raises an error:
text = "Python String"
text[0] = 'J' # Error
Correct way to create a modified string:
text = "Python String"
new_text = 'J' + text[1:]
print(new_text)
Output:
Jython String
More f-string Examples
name = 'Anthony'
message = f'Hello, {name}!'
print(message)
Output:
Hello, Anthony!
Explanation:
-
Use
f''
orf""
before the string -
Embed variables using
{}
Exercises
Exercise 1:
Create a string variable called city
with the name of your city. Use print()
to show a welcome message.
city = 'New York'
print(f'Welcome to {city}!')
Exercise 2:
Use string concatenation to create a greeting.
greeting = 'Hello'
name = 'Maria'
message = greeting + ', ' + name + '!'
print(message)
Exercise 3:
Access the first and last letters of a string using index and negative index.
word = 'Developer'
print('First letter:', word[0])
print('Last letter:', word[-1])
Exercise 4:
Slice a string to get a part of it.
language = 'JavaScript'
print('First four letters:', language[0:4])
Exercise 5:
Use f-strings to include variables in a string.
first_name = 'Lena'
last_name = 'Smith'
print(f'User: {first_name} {last_name}')
Summary
-
A string is a sequence of characters surrounded by quotes.
-
Strings can use either single or double quotes.
-
Use
\
to escape characters andr''
for raw strings. -
Use triple quotes for multiline strings.
-
Use f-strings (
f"{var}"
) to insert variables. -
Concatenate strings with
+
or by placing literals next to each other. -
Use
len()
to get the string’s length. -
Access individual characters with indexes (positive or negative).
-
Use slicing
string[start:end]
to extract substrings. -
Strings are immutable; create a new string to modify it.
-
Practice with exercises to reinforce what you've learned.
Copyright Statement: Unless stated otherwise, all articles are original to this site, please credit the source when sharing.
Article link:http://pybeginners.com/python-tutorial/python-strings/
License Agreement:Attribution-NonCommercial 4.0 International License