python string str learning summary

1. Representation of strings: enclose any string with quotation marks/double quotation marks

E.g:
a = 'abcd5sd6+f5as.x/dsf'
b = ''abcd5sd6+f5as.x/dsf''

You must know that the string str is a type that cannot be modified once it is created. The following additions, deletions, modifications and investigations are actually an operation that is proposed to modify and then reassign back.

2. Add, delete, modify and check strings

a. to increase

●You can add a string by direct assignment

b. delete

●It can be deleted by del + the string to be deleted. For example: del a

Remove the specified characters from the string in the specified order (from right to left, from left to right) (the specified character, if not entered, defaults to a space)

.lstrip() Remove the specified character from the left of the string
.rstrip() Remove the specified character from the left of the string
.strip() Head and tail are removed
 E.g:
 
 
a = '123456'
print(a.strip('615')
print(a.lstrip('1'))
print(a.rstrip('6'))			
It is also worth noting that the operation logic of this method is: split the string you specified to be removed (ie 615 in the above example), and match the original string (ie 123456) element by element.
For example, divide 615 into three elements, 6, 1, and 5, and match 123456 at both ends. On the
left: '1' belongs to one of 6, 1, and 5, and deletes it; followed by 2, which does not belong to 6, 1, and 5 Any of 5, so stop on the left
Right : '6' belongs to one of 6, 1, 5, delete; then 5, also belongs to one of 6, 1, 5, delete; next is 4, doesn't belong to any of the 3 of them, so stop, the result is '234'

c. Modify

(Why is it said that it cannot be modified and can also be written to modify, because the so-called 'modification' here is only the operation of extracting the string and assigning the new string (modified) back)

.format() [Replace the placeholder in the string with the specified content]
.format_map() [Replace the placeholder in the string with the specified content]
E.g:
a = 'my name is {name} , age is {age}.'
print(a.format(name = 'capture',age = 999))
b = 'my name is {0} , age is {1}.'
print(b.format('capture',999))
c = 'my name is {name} , age is {age}.'
print(c.format_map({'name':'capture','age':999}))					

percent sign splicing
%s Can receive all types of elements, returns a string
%d can only receive numbers
%f received decimal

 [The 's' here can be considered as the abbreviation of 'string', which is also the same as the above, and %s and %d here can be considered as placeholders]

E.g:

a = 'my name is %s, my age is %s.' %('capture','999') #%s can also be replaced by %.2s, %.3s, which means to intercept the first 2, 3 digits
b = 'There is a floating point number %.2f' %(92.15674891318913) #Here, %.2f is to keep two decimal places after the decimal point (rounding), and it is not omitted when entering %f
%' is used for string splicing because it is a slightly complicated system, and a chapter will be devoted to summarizing it.


.expandtabs() Replace all tabs in the string with spaces, so that the length of the string is extended by the specified length (the default is 8 if the number of tab spaces is not specified
This method will scan the string according to the specified length. When there is a tab character '\t' in the string of this length, it will be replaced with a space and the total length of the string including the space and the specified length will be equal to the specified length.
For example :
 
 
a = 'name\t age\t sex\nxiaoming\t 18\t nan\n'
b = 'name\t age\t sex\nxiaoming\t 18\t nan\nxiaoming\t 18\t nan\nxiaoming\t 18\t nan\nxiaoming\t 18\t nan\n'
print(a.expandtabs(30))
print(b.expandtabs(30))

●String case swap

.capitalize() capital letters
.casefold() The entire string becomes lowercase [casefold is more comprehensive than lower]
.lower() uppercase to lowercase
.upper() lowercase to uppercase
.swapcase() case swap

● String mapping and replacement

.maketrans() maketrans() and translate() are used together
.translate()  
.replace() (The character to be replaced in the original string, the new character, the maximum number of matches)

E.g:

a = 'one two three four five'
b = '12345'
c = str.maketrans(a,b) #Create a mapping relationship
d = b.replace('123','hahaha',3)
		
x = '156456418456428731536792'
y = x.translate(c)
print(y)
print(d)

d. Inquiry

First, because strings are iterable objects, we can disassemble the output with the help of for loops, and secondly, we can also output them in the form of indexes and slices

.count() (specify content, start position, end position) Counts the number of occurrences of the specified content in a string
.find() (specify content, start position, end position) Find the specified content in the string and output the position of its first occurrence in the string, if not found, output -1
.index() The same method as find(), the difference is that it will report an error if it cannot be found

a = 'abcdefgabcdefg'
print(a.count('bcd',4,10))
print(a.find('bcd',1,4))
#The count of the string here uses the method of "closed interval, open interval" (that is, the method of '(0,1]'), and it should be +1 when calculating the end position.


●Decoding and encoding of strings

.encode()         (the encoding to be converted, how to handle conversion errors) Convert the string to the specified encoding and return a bytes object
.decode()         (similar to encode usage) Convert the specified bytes object to the corresponding string
The default handling of .encode() is "strict", and all values ​​that can be written here are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any value registered via codecs.register_error()
For example:
a = 'You can really do whatever you want with money'
b = a.encode('utf-8')
print(b)
print(b.decode('utf-8'))				

3. Other methods of string str

a. Set a width fragment and center the string, left and right (width, padding)

.center() Centered
.light() left
.rjust () right
E.g:
a = 'abcd'
print(a.center(40,'will'))



b. Determine whether the string starts or ends with a specified content (specified content, start position, end position) [here returns a bool value]
.endswith() end
.startswith() beginning
E.g:
a = 'abcdefgh'
print(a.endswith('efg',2,7))
#Same as the count above, these two methods also use the "open interval, closed interval" method when calculating strings


c. A lot of judgment methods [return bool value]

.isalnum() Whether to contain only numbers and letters
.isalpha() Whether it is a letter (including Chinese characters)
.isdecimal() Is it a decimal number
.isdigit() Whether it is a number [larger range than .isdecimal()]
.isnumeric() Whether it is a digital value [larger than .isdigit()]
.isidentifier () Whether it is an identifier (for example, '_123' and 'def' return true, as long as it meets the requirements of variable names)
.isprintable () Whether all of them can be displayed (for example, \n\t in the string cannot be displayed, and these will output false)
.isspace() Is it all spaces [\t will also output true]
.ist Whether it is a title (English sentences with all capital letters will be considered as titles)
.isupper

Is it a capital letter

.islower() whether it is a lowercase letter

        d. Split each element in the string and join it into a new string (the split string) with the specified content. Join () Example:
    

a = 'I will starve to death, die outside, jump from here, and I won't learn python\nIt smells good'
b = '_'
print(b.join(a))
c = 'I starve to death, die outside, jump from here, and I won't learn python\nIt smells so good'
print('_'.join(c))

#Above is a single string, this time a tuple

d = ('我就是饿死','死外边','从这里跳下去','也不会学python','真香')
print('_'.join(d))

e.将字符串进行分割

.partition()  
.rpartition()  
.split() (指定要删除的字符串,匹配次数)
.rsplit()  
.splitlines() (ture和false #是否保留换行符)【.split()方法的变种,通过换行符来进行分割】


这里两个都是进行字符串分割,-r前缀代表从右往左的分割,split()方法分割字符串以后会把指定的那个字符串丢掉,而partition()方法不会且此方法指定次数只有一次

例如:

a = 'hedwsjfodiaspo'
print(a.partition('d'))
print(a.split('d',2))


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325728149&siteId=291194637