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

Format

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

Symbolic meaning

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

>>>'%.2f' % 0.33333
0.33

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 ’%’

>>>'{:%}'.format(3.5)
'350.0000%'

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:{
      value:{
      width}.{
      precision}}'#  Width and precision can be specified 
'result: 3.667'

Common functions

find,rfind,count, index,rindex

find(str,beg=0,end=len(str))
rfind(str,beg=0,end=len(str)))
index(str,beg=0,end=len(str)))
rindex(str,beg=0,end=len(str)))
count()
  • 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()、rsplit()、partition()、rpartition()

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)

join

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

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

lower()、upper()、capitalize()、title()、swapcase()

>>> s =
"What is Your Name?"
>>> s.lower() # Returns a lowercase string 
'what is your name?'
>>> s.upper() # Returns the uppercase string 
'WHAT IS YOUR NAME?'
>>> 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 
'wHAT IS yOUR nAME?'

replace()、maketrans()、translate()

replace

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 

maketrans()、translate()

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)

strip()、rstrip()、lstrip()

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

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')
''

startswith()、endswith()

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 
True
>>> s.startswith('Be', 5) # Specify the starting position of the detection range 
False
>>> s.startswith('Be', 0, 5) # Specify the start and end positions of the detection range 
True

isalnum()、isalpha()、isdigit()、isspace()、isupper()、islower()

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()
True
>>> '1234abcd'.isalpha() # Returns... When all letters are English True
False
>>> '1234abcd'.isdigit() # Returns... When all are numbers True
False
>>> 'abcd'.isalpha()
True
>>> '1234.0'.isdigit()
False

center()、ljust()、rjust()

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'

in

Member judgment , keyword in

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

*

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

>>> 'abcd' * 3
'abcdabcdabcd'

Built in functions for string objects

>>> x =
'Hello world.'
>>> len(x) # String length 
12
>>> max(x) # The largest character 
'w'
>>> 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.
https://en.pythonmana.com/2022/131/202205110611060965.html

Random recommended