Second, the road of python precipitation ~~ string attribute (str)

1. Usage of capitalize: Capitalize the first letter of the output string

1 test = "heLLo"
2 v = test.capitalize()
3 print(v)

Result: Hello.

2. The usage and difference between casefold and lower

1 test = "heLLo"
2 v1 = test.casefold()
3 print(v1)
4 v2 = test.lower()
5 print(v2)

Result: hello, hello. The result is the same, but the scope of application is different. casefold can recognize language conversions in most countries in the world, while lower is only suitable for English

3. The usage of center

1 test = "heLLo"
2 v3 = test.center(20)
3 print(v3)
4 v4 = test.center(20,"*")
5 print(v4)

result:

1        heLLo        
2 *******heLLo********

The output sets the width, and places the string in the middle, and can set padding on both sides.

4. Usage of count, endswith, startswith

1 test = " helloworldhello " 
2 v = test.count( " l " ) #Count the number of occurrences of l
 3 v1 = test.count( " l " ,3,5 ) #Count "l" in the range of 3 to 5 The number of occurrences
 4  print (v)
 5 v3 = test.endswith( " o " ) # Determine whether the string is "l" terminated, if it is, return True, otherwise return False
 6 v4 = test.endswith( " w " , 2,7 )# in the range of 2 to 7 to determine whether it ends with "w"
 7  print (v3)
 8  print (v4)
1 5
 2  True
 3 False

The usage of startswith is the same as endswith

5. The usage and difference of find and index

1 test = "helloworldhello"
2 v = test.find("w")
3 v1 = test.find("l")
4 print(v,v1)
5 v2 = test.find("l",6,10)
6 print(v2)
7 #v3 = test.index("l")
1 5 2
2 8

Both find and index are to find the position of a substring, and you can specify a range of search. The difference is that -1 is returned when find is not found, and an error is reported when index is not found

6, format and format_map format string usage

1 test = ' i an {name},age {a} ' 
2 test1 = ' i am {0},age{1} ' 
3 v = test.format(name= " zhongguo " ,a= ' 18 ' ) # Modification
 4 v1 = test1.format( " xiaoming " , ' 18 ' ) #Automatically match position
 5  print (v)
 6  print (v1)
 7 v2 = test.format_map({ " name " : ' zhong ' , 'a':18 }) The usage of #format_map is to add the content in the form of a dictionary in {}
 8  print (v2)
1 i an zhongguo,age 18
2 i am xiaoming,age18
3 i an zhong,age 18

 

Guess you like

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