Python string common operations

1. String separation

1.1 split() method

Function: the split() method starts from the left side of the string. The default split character is the space character, and the return value is the list.

For example: create a string str_1; Right str_1 and use the split() method

str_1 = 'a str of practice'
print(str_1.split())

The operation results are as follows:

['a', 'str', 'of', 'practice']

Of course, you can also change the default split character; We can change the parameter sep, such as creating a str_2 string, and string str_ The difference is that the separator between two English words is comma; Then we operate on the parameter sep as follows:

str_2 = 'a,str,of,practice'
print(str_2.split(sep=','))

The final operation result is the same as before:

['a', 'str', 'of', 'practice']

Another important parameter of the split() method is maxplit, which can specify the maximum number of splits. For example, we specify the maximum number of divisions as 1:

str_2 = 'a,str,of,practice'
print(str_2.split(sep=',',maxsplit=1))

The operation results are as follows

['a', 'str,of,practice']

1.2 resplit() method

The rsplit() method is the same as the split() method, except that the rsplit() method starts from the right and the split() method starts from the left.

2. Judgment method of string

2.1. isidentifier() method

isidentifier() can judge whether the string is a legal identifier, and the return value is Boolean. Legal identifiers are roughly composed of letters, numbers and underscores.

for example

str_3 = 'a str'
print(str_3.isidentifier())

The operation result is:

False

2.2 isspace() method

Judge whether the specified string is composed of all blank characters (line feed, carriage return, tab, etc.), and the return value is Boolean.

 

str_4 = '\t\n'
print(str_4.isspace())

The return value is:

True

2.3 isalpha() method

Judge whether the specified string is all composed of letters, and the return value is Boolean.

str_5 = 'practice'
print(str_5.isalpha())

The return value is:

True

2.4 isnumeric() method

Judge whether the specified string is all composed of numbers, and the return value is Boolean.

str_5 = '1234'
print(str_5.isalpha())

The return value is:

True

 

 3. String replacement and merging

 

3.1 replace() method

replace() method can replace strings. The first parameter specifies the substring to be replaced and the second parameter specifies the string to replace the substring. This method returns the string obtained after replacement. The string before replacement does not change. The third parameter calling this method specifies the maximum number of replacements.

str_6 = 'An exercise'
print(str_6.replace('one','two'))
str_7 = 'An exercise'
print(str_7.replace('practice','test'))#Do not specify the maximum number of replacements
print(str_7.replace('practice','test',1))#Specifies that the maximum number of replacements is 1

Output is:

Two exercises
 A test
 A test exercise

3.2. join() method

String merging: merge the strings in the list or tuple into one string;

str_8 = ['practice','perhaps','test']
print(' '.join(str_8)) #Merge with spaces
print('*'.join(str_8))#Merge with *
#Use of tuples
str_9 = ('practice','perhaps','test')
print(' '.join(str_9)) #Merge with spaces

#Directly join the string
print(' '.join('practice'))
#Merge with spaces

Operation results:

Practice or test
 practice*perhaps*test
 Practice or test
p r a c t i c e

 

4. String query

Since the query is relatively simple, no operation will be performed here.

4.1 index() and rindex() methods

The two methods find the position of the first and last occurrence of the substring respectively. Throw ValueError if the substring found does not exist

4.2 find() and rfind() methods

The two methods find the position of the first and last occurrence of the substring respectively. If the substring found does not exist, - 1 is returned.

5. Case conversion of string

5.1 upper() method

Converts all characters in a string to uppercase letters.

5.2 lower() method

Converts all characters in a string to lowercase letters.

5.3 swapcase() method

Convert the lowercase letters in the string to uppercase letters, and convert the uppercase letters in the string to lowercase letters.

5.4 capitalization () method

Convert the first character to uppercase and the rest to lowercase.

str_10 = 'adsdaEsad'
print(str_10.capitalize())

The result is as follows: it converts the initial a to a and all letters including E to lowercase.

Adsdaesad

5.5 title() method

Convert the first character of each word to uppercase and the remaining characters to lowercase.

str_11 = 'a str of practice'
print(str_11.title())

The results are as follows:

A Str Of Practice

6. Alignment of string contents

6.1 center method

Function: the position is centered. The first parameter specifies the length, and the second parameter specifies the filler (blank by default),

If the set length is less than the actual length, the length of the original string is returned.

str_12 = 'practice'
print(str_12.center(10,'$'))

String str_ The length of 12 is 8. When the specified length is set to 10, use $to supplement one on the left and right. The specific operation results are as follows:

$practice$

6.2 ljust() method and rjust() method

These two methods correspond to left alignment and right alignment respectively,

The second parameter specifies the filler (the default is space). If the set length is less than the actual length, the length of the original string will be returned.

str_12 = 'practice'
print(str_12.ljust(10,'$'))#Left justified, filled with $
print(str_12.rjust(10))#Right justified, filled with spaces

Right str_12. Align left and right. The results are as follows:

practice$$
  practice

6.3 zfill() method

Function: align right and fill the left with 0. This method only accepts one parameter: specify the length

If the set length is less than the actual length, the length of the original string is returned.

str_12 = 'practice'
print(str_12.zfill(10))

The operation results are as follows:

00practice

 7. format string

7.1% as placeholder

For example: we want to call Xiao Hong out. This can be done in python:

grade = 2
name  = 'Xiao Hong'
print('%d Grade%s Come out for a minute'%(grade,name))

Where% is a placeholder,% d can be understood as taking a position for an integer, and% s is taking a position for a string.

The operation results are as follows:

2 Little red from grade one, come out

7.2 {} as placeholder

The format() method is used here.

For example:

grade = 2
name  = 'Xiao Hong'
print('I am{0},Last year{1}Grade, there is another one in our class{0}'.format(name,grade))
print(f'I am{name},Last year{grade}Grade, there is another one in our class{name}')

The operation results are as follows:

I'm Xiaohong. I'm in grade 2 this year. There's another Xiaohong in our class
 I'm Xiaohong. I'm in grade 2 this year. There's another Xiaohong in our class

8. String encoding and decoding

code:

str_13 = 'I'm Xiao Hong'
print(str_13.encode(encoding='gbk'))#Chinese data in GBK format takes up two bytes
print(str_13.encode(encoding='utf8'))#The Chinese data in UTF-8 format occupies three bytes

The operation results are as follows:

b'\xce\xd2\xca\xc7\xd0\xa1\xba\xec'
b'\xe6\x88\x91\xe6\x98\xaf\xe5\xb0\x8f\xe7\xba\xa2'

b stands for binary;

Decoding (the encoding format should be the same as the decoding format, otherwise an error will be reported):

en = str_13.encode(encoding='gbk')
print(en.decode(encoding='gbk'))

The operation results are as follows:

I'm Xiao Hong

Here are some of my study notes. Welcome to give advice and exchange!

Keywords: Python Back-end

Added by atl_andy on Tue, 22 Feb 2022 14:49:30 +0200