Working with Strings in Python
In this chapter, the theme is strings.
You will learn several ways to work with and write strings in Python.
What Is a String?
A string is, as the name suggests, a sequence of characters.
In Python, strings are usually written using double quotes (" ") or single quotes (' ').
In the examples below, the output is the same in both cases.
print("Hello, Python!!") # Hello, Python!!
print('Hello, Python!!') # Hello, Python!!
Concatenating Strings
You can use + to concatenate (join) strings together.
print("Hello, " + "Python!!") # Hello, Python!!
You can also concatenate strings by placing them next to each other.
This is especially useful when joining long strings.
print(
"Hello, "
"Python!!"
) # Hello, Python!!
Repeating Strings
You can use * to repeat a string multiple times.
print("Hello, " * 3 + "Python!!")
# Hello, Hello, Hello, Python!!
Newlines and Special Characters
Some characters have special meanings inside strings.
They are written using a backslash (\) and are called escape sequences.
print("Hello, \nPython!!") # \n = newline
# Hello,
# Python!!
print("Hello, \tPython!!") # \t = tab
# Hello, Python!!
print("Hello, \\Python!!") # Use \\ to display a backslash
# Hello, \Python!!
Checking the Length of a String
To check the length of a string (the number of characters), use the len() function.
print(len("Hello, Python!!")) # 16
Extracting Parts of a String
If you want to extract part of a string, use slicing.
In Python, indexing starts from 0.
message = "Hello, Python!!" # Store the string in a variable (explained in a later chapter)
print(message[0:6]) # Hello (from index 0 to 5)
print(message[6:]) # , Python!! (from index 6 to the end)
print(message[:10]) # Hello, Py (from the start to index 9)
print(message[-1:]) # ! (last character)
print(message[-3:]) # !!! (last 3 characters)
String Formatting
Finally, let’s introduce a very useful feature called string formatting.
lang1 = "Python"
lang2 = "JavaScript"
lang3 = "C++"
print(f"Hello, {lang1} and {lang2} and {lang3}!!")
# Hello, Python and JavaScript and C++!!
Coming Up Next...
Thank you very much for reading!
The next chapter is titled “Working with Variables”.
Stay tuned!
Top comments (0)