The Python string

The target

In this article, you’ll learn about Python strings and their basic operations.

Introduction to Python Strings

A string is a string of characters. In Python, anything inside quotes is a string. You can use single or double quotation marks. Such as:

Message = 'This is a string' message = 'this is also a string'Copy the code

If a string contains single quotes, you should put it in double quotes, like this:

Message = "It's a string"Copy the code

Single quotes can be used when a string contains double quotes:

Message = 'it is a string'Copy the code

To escape quotes, use a backslash (). Such as:

Message = '\' is single quote 'Copy the code

The Python interpreter treats the backslash character () specially. If you don’t want to do this, you can use the raw string by adding the letter R before the first quotation mark. Such as:

message = r'C:\python\bin'
Copy the code

Create a multi-line string

To extend a string to multiple lines, use triple quotes “””…” “” “or “‘… “‘. Such as:

help_message = '''
Usage: mysql command
    -h hostname     
    -d database name
    -u username
    -p password 
'''

print(help_message)
Copy the code

If you execute this program, it will print the following:

Usage: mysql command
    -h hostname
    -d database name
    -u username
    -p password
Copy the code

Use variables with f strings in Python strings

Sometimes you want to use the value of a variable in a string.

For example, you might want to use the value of the name variable in the message string variable:

name = 'xiaoming'
message = 'Hi'
Copy the code

To do this, you need to place the letter F before the open quotation mark and surround the variable name with curly braces:

name = 'xiaoming'
message = f'Hi {name}'
print(message)
Copy the code

Python replaces {name} with the value of the name variable. The code will display the following on the screen:

Hi xiaoming
Copy the code

The message is a format string, referred to simply as an F string. Python introduced the F string beginning with version 3.6.

Python string concatenation

When you place string literals next to each other, Python automatically concatenates them into a single string. Such as:

greeting = 'Good ' 'Morning! ' print(greeting)Copy the code

Output:

Good Morning!
Copy the code

To concatenate two string variables, use the + operator:

greeting = 'Good ' time = 'Afternoon' greeting = greeting + time + '! ' print(greeting)Copy the code

Output:

Good Afternoon!
Copy the code

Accessing string elements

Because a string is a string of characters, its elements can be accessed using an index. The subscript of the first character in the string is zero.

The following example shows how to use indexes to access elements:

str = "Python String"
print(str[0]) # P
print(str[1]) # y
Copy the code

How it works:

  • First, create a save string"Python string"The variables.
  • Then, use square brackets[]And index to access the first and second characters of the string.

If negative indexes are used, Python returns characters starting at the end of the string. Such as:

str = "Python String"
print(str[-1])  # g
print(str[-2])  # n
Copy the code

The following shows the index 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-11-12-13-10-9-8-7-4-3-5-6 - 2-1Copy the code

Gets the length of the string

To get the length of the string, use the len() function. Such as:

str = "Python String"
str_len = len(str)
print(str_len)
Copy the code

Output:

13
Copy the code

String slice

Slicing allows you to get substrings from strings. Such as:

str = "Python String"
print(str[0:2])
Copy the code

Output:

Py
Copy the code

STR [0:2] returns a substring containing characters from indexes 0(inclusive) through 2(exclusive).

The syntax for slicing is as follows:

String [Start: End]Copy the code

Substrings always contain the beginning character but not the end character.

The beginning and end are optional. If the start is omitted, it defaults to zero. If the end is omitted, the default is the length of the string.

Python strings are immutable

Python strings are immutable. That means you can’t change strings. For example, if you update one or more characters in a string, you’ll get an error:

str = "Python String"
str[0] = 'J'
Copy the code

Error:

Traceback (most recent call last): File "c:\Users\nasoul\Desktop\tutorial\Python\ first \ helloWorld \app.py", line 2, in <module> STR [0] = 'J' TypeError: 'str' object does not support item assignmentCopy the code

When you need to modify a string, you need to create a new string from an existing string. Such as:

str = "Python String"
new_str = 'J' + str[1:]
print(new_str)
Copy the code

Output:

Jython String
Copy the code

conclusion

  • In Python, a string is a string of characters. Furthermore, Python strings are immutable.
  • Use quotation marks, single or double quotation marks to create string literals.
  • Use the backslash character \ to escape quotes in strings
  • Using the raw string r’… ‘to escape the backslash character.
  • Inserts substitution variables into string literals using f strings.
  • Place literal strings next to each other to concatenate them. And concatenate string variables using the + operator.
  • uselen()The function gets the size of the string.
  • usestr[n]Access the character at position n in the string STR.
  • Extract substrings from strings using slices.