current position:Home>Python course notes -- Python string, detailed explanation of related functions

Python course notes -- Python string, detailed explanation of related functions

2022-05-15 05:50:00Tang Keke, Laoxiang, Henan

String encoding

  • GBK2312 It is the Chinese code formulated by our country , use Two bytes for Chinese
  • Unicode Put all languages into one set of codes , There will be no garbled code , Two bytes represent a character , Four characters are used for remote words
  • UTF-8 It encodes the characters needed all over the world , yes “ Variable length encoding ”, Use a byte to represent the letter , Three bytes represent Chinese , Others are two or four bytes .

Python3.x Version default use UTF-8 Format encoding

Escape character

You put it in front of the string ’r’, perhaps ’R’, Indicates that the following string will not be escaped .

path = r'C:\windows\python.exe'

Formatting of strings

% format


print('%d %s' % (a, b)) 

Symbolic meaning

‘-’ Specify left alignment
‘+’ Add before positive number + Number
‘.n’ Specify the precision

>>>'%.2f' % 0.33333

Format characters

and C++ Basically the same ,

  • %d Decimal integer
  • %e With e Bottom index
  • %o Octal integer

format() Method to format

The basic grammar is through ’{}’,’:‘ Replace the previous ’%’


The meaning of characters in various formats

Specify location parameters

"{}{}".format('Hello', 'World') #  By default 
>>> "{0}{1}{0}".format('Hello', 'World'') #  The specified location 
'World Hello World’
>>> print("my name is {
    name}, my age is {
    age}, and my QQ is
    qq}".format(name = "Dong Fuguo",age = 40,qq = "30646****")) #  Variable naming 
my name is Dong Fuguo, my age is 40, and my QQ is 30646****

String preceded by f

And format The method is basically similar to

>>> name = 'Dong'
>>> age = 39
>>> f'My name is {
      name}, and I am {
      age} years old.'
'My name is Dong, and I am 39 years old.'

>>> width = 10
>>> precision = 4
>>> value = 11/3
>>> f'result:{
      precision}}'#  Width and precision can be specified 
'result: 3.667'

Common functions

find,rfind,count, index,rindex

  • find() and rfind Methods are used to find a string within the specified range of another string ( The default is the entire string ) The position of the first and last appearance in , Returns if it does not exist -1
  • index() and rindex() Method is used to return the position of the first and last occurrence of one string in the specified range of another string , If it doesn't exist Throw an exception
  • count() Method is used to return the number of times a string appears in the current string


split(str="", num=string.count(str))、rsplit(str="",num=string.count(str))
  • split() and rsplit() Methods are used to separate with the specified character , Separate the current string from left to right or from right to left into multiple strings , And return a list of delimited results
  • partition() and rpartition() Used to separate the original string with the specified string as the separator Divided into 3 part , namely String before separator 、 Separator string 、 String after separator , If the specified delimiter is not in the original string , Then return to The original string and two empty strings . Put the string string branch become One individual 3 element plain Of Tuples (string_pre_str,str,string_post_str)


Returns a new string generated by connecting elements in a sequence through a specified character .

>>> li = ["apple","peach","banana","pear"]
>>> ','.join(li)


>>> s =
"What is Your Name?"
>>> s.lower() # Returns a lowercase string 
'what is your name?'
>>> s.upper() # Returns the uppercase string 
>>> s.capitalize() # The first character of a string is capitalized 'What is your name?'
>>> s.title() # Capitalize each word 'What Is Your Name?'
>>> s.swapcase() # Case interchangeability 



Search and replace replace(old, new[, max]), Be similar to Word Medium “ All replacement ” function

  • old – Substring to be replaced
  • new – New string , Used for replacement old Substring
  • max – Optional string , Replace no more than max Time

Be careful : It returns a new string

>>> s =" China , China "
>>> print(s)
 China , China 
>>> s2 = s.replace(" China "," The People's Republic of China ")
>>> print(s2)
 The People's Republic of China , The People's Republic of China 


String object maketrans() Method is used to generate a character mapping table , and translate() Method is used to convert a string according to the correspondence defined in the mapping table and replace the characters in it , Using a combination of these two methods, you can process multiple characters at the same time .

# Create a mapping table , The character "abcdef123" Convert one-to-one into "[email protected]#$"
>>> table =
''.maketrans('abcdef123','[email protected]#$')
>>> s ="Python is a greate programming language. I like it!"
# Replace by mapping table 
>>> s.translate(table)
'Python is u gryuty progrumming lunguugy. I liky it!'

Some commonly used whole letters , And realize Caesar encryption

lower = string.ascii_lowercase # Lowercase letters 
upper = string.ascii_uppercase # Capital 
before = string.ascii_letters
after = lower[k:] + lower[:k] + upper[k:] + upper[:k]
table =''.maketrans(before, after) # Create a mapping table  
return s.translate(table)


>>> s =" abc "
>>> s.strip() # Delete white space characters 
>>> '\n\nhello world \n\n'.strip() # Delete white space characters 
'hello world'
>>> "aaaassddf".strip("a") # Delete specified characters 
>>> "aaaassddf".strip("af")
>>> "aaaassddfaaa".rstrip("a") # Delete the specified character at the right end of the string 
>>> "aaaassddfaaa".lstrip("a") # Delete the specified character at the left end of the string 

Be careful , The strings specified by the parameters of these three functions are not treated as a whole , But on both sides of the original string 、 On the right side 、 Delete all characters contained in the parameter string on the left

>>> 'aabbccddeeeffg'.strip('gbaefcd')


s.startswith(t, beg=0,end=len(string))、s.endswith(t,beg=0,end=len(string)), Determines whether a string starts or ends with a specified string

>>> s = 'Beautiful is better than ugly.'
>>> s.startswith('Be') # Detect the entire string 
>>> s.startswith('Be', 5) # Specify the starting position of the detection range 
>>> s.startswith('Be', 0, 5) # Specify the start and end positions of the detection range 


isalnum()、isalpha()、isdigit()、isspace()、isupper()、islower(), Used to test whether the string is a number or letter 、 Is it a letter 、 Whether it is a numeric character 、 Whether it is a blank character 、 Whether it is uppercase and lowercase .

>>> '1234abcd'.isalnum()
>>> '1234abcd'.isalpha() # Returns... When all letters are English True
>>> '1234abcd'.isdigit() # Returns... When all are numbers True
>>> 'abcd'.isalpha()
>>> '1234.0'.isdigit()


center()、ljust()、rjust(), Returns a new string of the specified width , The original string is centered 、 Left or right alignment appears in the new string , If the specified width is greater than the string length , Then use the specified character ( Default is space ) Fill in .

>>> 'Hello world!'.center(20) # Align center , Fill with spaces 
' Hello world! '
>>> 'Hello world!'.center(20,'=') # Align center , In characters = Fill in 
'====Hello world!===='
>>> 'Hello world!'.ljust(20,'=') # Align left 
'Hello world!========'
>>> 'Hello world!'.rjust(20,'=') # Right alignment 
'========Hello world!'

String supported operators


Generate a new string

>>> 'hello ' + 'world'
'hello world'


Member judgment , keyword in

>>> "a" in "abcde" # Test whether one character exists in another string 
>>> 'ab' in 'abcde'
>>> 'ac' in 'abcde' # keyword in The string on the left is treated as a whole 
>>> "j" in "abcde"


Python Strings support multiplication with integers , Indicates sequence duplication , That is, the repetition of string content , Get the new string

>>> 'abcd' * 3

Built in functions for string objects

>>> x =
'Hello world.'
>>> len(x) # String length 
>>> max(x) # The largest character 
>>> min(x)
' '
>>> list(zip(x,x)) #zip() It can also act on strings 
[('H','H'), ('e','e'), ('l','l'), ('l','l'), ('o','o'), (' ','',('w','w'), ('o','o'), ('r','r'), ('l','l'), ('d','d'), ('.','.')]
>>> sorted(x)
[' ','.','H','d','e','l','l','l','o','o','r','w']
>>> list(reversed(x))
['.','d','l','r','o','w',' ','o','l','l','e','H']
>>> list(enumerate(x))
[(0,'H'), (1,'e'), (2,'l'), (3,'l'), (4,'o'), (5,' '), (6,'w'),(7,'o'), (8,'r'), (9,'l'), (10,'d'), (11,'.')]
>>> list(map(add, x, x))
['HH','ee','ll','ll','oo',' ','ww','oo','rr','ll','dd','..']

copyright notice
author[Tang Keke, Laoxiang, Henan],Please bring the original link to reprint, thank you.

Random recommended