current position:Home>Chapter 2: Fundamentals of python-3 character string

Chapter 2: Fundamentals of python-3 character string

2022-01-30 08:51:09 Small horn

Python character string

The goal is

In this article , You will learn Python String and its basic operations .

Python String Introduction

A string is a string of characters . stay Python in , Anything in quotation marks is a string . You can use single quotation marks or double quotation marks . for example :

message = ' This is a string '
message = " This is also a string "
 Copy code 

If a string contains single quotes , You should put it in double quotation marks , like this :

message = " It's a string "
 Copy code 

When the string contains double quotes , You can use single quotes :

message = '" It's a string "'
 Copy code 

To escape quotation marks , You can use backslashes (). for example :

message = '\' Is single quotes '
 Copy code 

Python The interpreter will interpret the backslash character () Special treatment . If you don't want to , You can add letters before the first quotation mark r To use the original string . for example :

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

Create a multiline string

To extend a string to multiple lines , You can use triple quotes """..."""" or '''...'''. for example :

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

print(help_message)
 Copy code 

If you execute this program , It will output the following :

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

stay Python Use... In string f Strings use variables

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

for example , You may want to be message Use... In string variables name The value of the variable :

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

Do that , You need to put the letters f Put it in front of the opening quotation mark , And put braces around the variable name :

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

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

Hi xiaoming
 Copy code 

The message is a format string , Referred to as f character string .Python from 3.6 Version started f character string .

Python String connection

When you place string literals next to each other ,Python They are automatically concatenated into a string . for example :

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

Output :

Good Morning!
 Copy code 

To connect two string variables , You can use the operator +:

greeting = 'Good '
time = 'Afternoon'

greeting = greeting + time + '!'
print(greeting)
 Copy code 

Output :

Good Afternoon!
 Copy code 

Access string elements

Because a string is a string of characters , So you can use the index to access its elements . The subscript of the first character in the string is zero .

The following example shows how to use an index to access elements :

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

How it works :

  • First , Create a save string “Python string” The variable of .
  • then , Use square brackets [] And index access the first and second characters of the string .

If you use a negative index ,Python Will return characters starting from the end of the string . for example :

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

The following demonstrates the string "Python string" The index of :

+---+---+---+---+---+---+---+---+---+---+---+---+---+
| 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 
 Copy code 

Gets the length of the string

To get the length of the string , have access to len() function . for example :

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

Output :

13
 Copy code 

String slice

Slicing allows you to get substrings from strings . for example :

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

Output :

Py
 Copy code 

str[0:2] Returns an index containing from 0( Include ) To 2( barring ) Substring of characters .

The syntax of slicing is as follows :

 character string [ Start : end ]
 Copy code 

Substrings always contain Start Characters that do not contain end The characters of .

Start and end It's optional . If omitted Start , It defaults to zero . If omitted end , The default is the length of the string .

Python Strings are immutable

Python Strings are immutable . This means you can't change the string . for example , If you update one or more characters in a string , You will get a mistake :

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

error :

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

When you need to modify the string , You need to create a new string from an existing string . for example :

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

Output :

Jython String
 Copy code 

summary

  • stay Python in , A string is a string of characters . and ,Python Strings are immutable .
  • Use quotation marks , Creates a single or double quotation mark literal string .
  • Use the backslash character \ Escape quotation marks in string
  • Use original string r'...' Escape the backslash character .
  • Use f String inserts an alternate variable into the string literal .
  • Place literal strings adjacent to each other to connect them . And use + Operator concatenates string variables .
  • Use len() Function to get the size of the string .
  • Use str[n] Access string str Located in n The character of position .
  • Use slicing to extract substrings from strings .

copyright notice
author[Small horn],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201300851057885.html

Random recommended