In this article, we will learn the concept of Python string and its basic operation.
Python string
A string is a sequence of characters. In Python, the content in quotation marks is a string. Quotation marks can be single quotation marks or double quotation marks. For example:
message = 'This is a string in Python' message = "This is also a string"
If a string itself contains single quotation marks, you can use double quotation marks:
message = "It's a string"
Similarly, if a string itself contains double quotation marks, you can use single quotation marks:
message = '"Beautiful is better than ugly.". Said Tim Peters'
In addition, we can escape quotation marks with a backslash (\). For example:
message = 'It\'s also a valid string'
The Python interpreter takes special care of backslashes. If you do not want to deal with the backslash in the string, you can add a letter r in front of the string to indicate that the original string (raw string) is used. For example:
message = r'C:\python\bin'
Create multiline string
If you want to specify a cross line string, you can use triple single quotation marks ('') or triple double quotation marks (""). For example:
help_message = ''' Usage: mysql command -h hostname -d database name -u username -p password ''' print(help_message)
The output information of the above code is as follows:
Usage: mysql command -h hostname -d database name -u username -p password
Using variables in strings
Sometimes we want to use the value of a variable in a string. For example, we want to use the value of the name variable in the message string variable:
name = 'John' message = 'Hi'
To do this, we can add the letter f at the beginning of the string, and then use braces to refer to the variable name:
name = 'John' message = f'Hi {name}' print(message)
The Python interpreter will replace {name} with the value of the variable name. The results of the above code are as follows:
Hi John
The message in the above example is a formatted character type, called f-string for short. Python 3.6 introduced f-string.
Connection string
When we separate multiple string constants with spaces, Pyrhon will automatically connect them into a string. For example:
greeting = 'Good ' 'Morning!' print(greeting)
Output result input:
Good Morning!
If you want to connect two variables, you can use the + operator:
greeting = 'Good ' time = 'Afternoon' greeting = greeting + time + '!' print(greeting)
The input results are as follows:
Good Afternoon!
Access string elements
A string is a sequence of characters, so we can access the elements in the string through subscripts. The subscript of the first element in the string is 0.
The following example demonstrates how to access string elements through subscripts:
str = "Python String" print(str[0]) # P print(str[1]) # y
The processing procedure of the above code is as follows:
- First, create a variable and assign it "Python String".
- Then, the first and second characters in the string are accessed through square brackets ([]) and subscripts.
If a negative number is specified as the subscript, Python will calculate from the right side of the string and return the corresponding character. For example:
str = "Python String" print(str[-1]) # g print(str[-2]) # n
The following are all subscripts of the string "Python String":
+---+---+---+---+---+---+---+---+---+---+---+---+---+ | 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
If the specified subscript is outside the range of the string, an error will be returned:
str = "Python String" print(str[13]) Traceback (most recent call last): File "<pyshell#1>", line 1, in <module> print(str[13]) IndexError: string index out of range
Gets the length of the string
If you want to get the length of the string, you can use the len() function. For example:
str = "Python String" str_len = len(str) print(str_len)
The output results are as follows:
13
Get substring
Slicing can return substrings in a string. For example:
str = "Python String" print(str[0:2])
The output results are as follows:
Py
str[0:2] returned a substring from subscript 0 (included) to subscript 2 (not included).
The syntax of string slicing operation is as follows:
string[start:end]
The substring contains the characters corresponding to the subscript start, but does not contain the characters corresponding to the subscript end.
The parameters start and end are optional. If start is omitted, it means starting from subscript 0; If end is omitted, all subsequent characters are returned.
String immutable
A Python string is an immutable object, which means that we cannot change the value of the string. For example, the following example wants to modify a character in a string and returns an error:
str = "Python String" str[0] = 'J' Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> str[0] = 'J' TypeError: 'str' object does not support item assignment
If you want to modify the string, we can create a new string based on the existing string. For example:
str = "Python String" new_str = 'J' + str[1:] print(new_str)
The output results are as follows:
Jython String
summary
- Python strings are sequences of characters, and strings are immutable objects.
- Use single or double quotation marks to define string constants.
- Use a backslash (\) to escape quotation marks in a string.
- Use the original string (r '...') to escape the backslash in the string.
- Use format strings (f-strings) to insert alternative variables into string constants.
- Use spaces to automatically connect multiple string constants, and use the + operator to connect multiple string variables.
- Use the built-in len() function to get the length of the string.
- Use str[n] to access the character corresponding to subscript n in string str.
- Get substrings using string slicing.