r grammar
Adding R or R to the front of the string can eliminate the function of all escape characters in the string (each symbol comma is programmed with ordinary characters)
str1 = r'C:\Users\name\test\demo.py' print(str1) # C:\Users\name\test\demo.py
String formatting
1. Format string
Syntax: String% containing format placeholder (data1, data2,...)
1) % s - string placeholder
%s can occupy any type of data
str1 = '%sxx' % 'you' print(str1) # You xx str1 = '%s-xxx' % [10, 20] print(str1) # [10, 20]-xxx
2) % d - integer placeholder
%d any digital data can be occupied
str1 = '%d-xxx' % 23 print(str1) # 23-xxx str1 = '%d-xxx' % 12.5 print(str1) # 12-xxx
3) % f - floating point placeholder (six decimal places)
%f can occupy any digital data
str1 = '%fxx' % 4.34 print(str1) # 4.340000xx str1 = 'balance:%.2f' % 3452233.1515 print(str1) # Balance: 345223.15
2.f-string
- Syntax: f '{any resulting expression}' - fill the position of {} with the result of the expression
- Add parameter
- . Nf - controls the number of decimal places
- , - Bank amount separated form
- . n% - convert the number to percentage, and keep N decimal places for the ratio
- x > N: convert the data into a string of length N. if it is not enough, fill it with the character corresponding to x in front
- x < N: convert the data into a string of length N. if not enough, fill it with the character corresponding to x
1) Basic usage
str1 = f'{name}-{age}-{age * 10}-{name[-1]}' print(str1) # Xiaoming-18-180-ming
2) Parameters
a. .Nf
money = 2305 str1 = f'amount of money:{money:.2f}' print(str1) # Amount: 2305.00
b. ,
money = 2349000 str1 = f'Balance:{money:,}' print(str1) # Balance: 2349000
c. .N%
rate = 0.5 str1 = f'Duration occupancy:{rate:.2%}' print(str1) # Duration occupancy: 50.00%
d. x > N x < N
<, > - decide whether to fill in the front or the back
x - fill character
N - target length
num = 9 str1 = f'Python2106{num:0>3}' print(str1) # Python2106009 str1 = f'Python2106{num:0<3}' print(str1) # Python2106900
correlation function
1.center,rjust,ljust,zfill
- String. Center (len gt h, padding character), for example: 'abc'. center(7, 'x') – > 'xxabcxx'
- String. Rjust (len gt h, padding character), for example: 'abc'. rjust(7, 'x') – > 'xxxabc'
- String. Ljust (len gt h, padding character), for example: 'abc'. ljust(7, 'x') – > 'abcxxxx'
- String. Zfill (length) = = string. Rjust (length '0'), e.g. 'ABC'. zfill(7) – > '0000abc'
print('abc'.center(7, 'x')) # xxabcxx print('abc'.rjust(7, 'x')) # xxxxabc print('abc'.ljust(7, 'x')) # abcxxxx print('abc'.zfill(7)) # 0000abc
2.count
- String 1. Count (string 2) - counts the number of occurrences of string 2 in string 1
- String 1. Count (string 2, start subscript, end subscript): counts the number of occurrences of string 2 in the range from the start subscript to the end subscript (not available) in string 1
str1 = 'how are you? u am fine, thank you! and you?' print(str1.count('a')) # 4 print(str1.count('you')) # 3 print(str1.count('a', 0, 12)) # 1
3.find/rfind,index/rindex
- String 1. Find (string 2) - get the first occurrence position of string 2 in string 1, and return the subscript value starting from 0; Returns - 1 if string 2 does not exist
- String 1. Index (string 2) - get the first occurrence position of string 2 in string 1, and return the subscript value starting from 0; If string 2 does not exist, an error is reported
- String 1.find (string 2, start subscript, end subscript), string 1.find (string 2, start subscript, end subscript)
str1 = 'how are you? i am fine, thank you! and you?' str1 = 'how are you? i am fine, thank you! and you?' print(str1.find('you')) # 8 print(str1.rfind('you')) # 39 print(str1.index('you')) # 8 print(str1.rindex('you')) # 39 print(str1.find('you1')) # -1 # print(str1.index('you1')) # report errors print(str1.find('a', 4, 12)) # 4 print(str1.index('y', 3, 25)) # 8
4.isdigit(),isnumeric()
- String. isdigit() - judge whether it is a pure numeric string (numbers refer to numeric characters from 0 to 9)
- String. isnumeric() - judge whether it is a pure numeric string (a number is a character with numeric meaning)
print('234234'.isdigit()) # True print('234234'.isnumeric()) # True print('23 One million twelve⑤'.isnumeric()) # True
5.islower,isupper
- String. islower() - determines whether the string is a pure lowercase character string
- String. upper() - determines whether the string is a pure uppercase string
print('asda'.islower()) # True print('SFAF'.isupper()) # True
6.join
- String. Join (sequence) - splices the elements in the sequence into a new string with the specified string
Note: the elements in the sequence must be strings
result = '+'.join('abc') print(result) # a+b+c result = '+'.join(['name', 'Xiao Ming']) print(result) # name + Xiao Ming result = ''.join(['name', 'Xiao Ming']) print(result) # name Xiaoming
Exercise: combine the elements in the list into a string
['abc', 100, 12.5, True, 'hello'] -> 'abc10012.5Truehello'
list1 = ['abc', 100, 12.5, True, 'hello'] result = ''.join([str(i) for i in list1]) # abc10012.5Truehello
Exercise 2: the scores of multiple students have been saved in a list. Extract the names of all students and return them as a string
[{name ':' Zhang San ',' age ': 18}, {name':'xiaoming ',' age ': 20}, {name':'xiaohua ',' age ': 30}] - >' Zhang San, Xiaoming, Xiaohua '
list1 = [{'name':'Zhang San', 'age': 18}, {'name':'Xiao Ming', 'age': 20}, {'name':'floret', 'age': 30}] result = ','.join([str(stu['name']) for stu in list1]) # Zhang San, Xiao Ming, Xiao Hua
7.strip,lstrip,rstrip
- String. strip() - remove white space characters at both ends of the string
- String. lstrip() - remove the white space character in front of the string
- String. rstrip() - remove the white space characters after the string
str1 = ' \tabc i 123 \n' result = str1.strip() print('==', result, '===', sep='') result = str1.lstrip() print('==', result, '===', sep='') result = str1.rstrip() print('==', result, '===', sep='')
8.replace
- String 1. Replace (string 2, string 3) - replaces all string 2 in string 1 with string 3
- String 1. Replace (string 2, string 3, N) - replaces the first N string 2 in string 1 with string 3
str1 = 'how are you? i am fine, thank you! and you?' result = str1.replace('u', 'b', 2) print(result) # how are yob? i am fine, thank yob! and you?
9.maketrans,translate
Str.maketrans (string 1, string 2) - create a character correspondence table for string 1 and string 2
table = str.maketrans('ain', 'You me him') # a - you, i - me, n - him result = str1.translate(table) print(result) # how you re you? I you m f I he e, th you he k you! You him d you?
Exercise: replace all Arabic numerals in the string with corresponding Chinese numerals
'123 wooden man, 88' - > '123 wooden man, 88'
table = str.maketrans('0123456789', 'zero one two three four five six seven eight nine') str1 = '123 Wooden man, 88' result = str1.translate(table) print(result) # One, two, three, eight
10.split
String 1.split (string 2) - cut the string using all string 2 in string 1 as the cut point
str1 = 'how are you? i am fine, thank you! and you?' result = str1.split('you') print(result) # ['how are ', '? i am fine, thank ', '! and ', '?']
Note: if the cutting point is at the front or back, or there is a cutting point for practice, an empty string will appear
str2 = 'amnayouaa==a123aklpa' print(str2.split()) # ['', 'mn', 'you', '', '==', '123', 'klp', '']