Today saw on the public micro-channel number of the article again python learning development, there are a number of questions face the python, python do not know what happened recently learned, simply learn about this article ah! ! The first to write about some strings commonly used functions. (Ps: I have too much food, if the wrong place at any time to welcome chiefs scolded ..xixixii)
0x01: format string
Format string can be very helpful to us what we want out of output, it is also very easy to use, there are several forms below.
# Format string print ( 'hello, {0} {1} {2}'. format ( 'zhong', 'yuan', 'gong')) # formatted by the position print ( 'hello, {name}, my name is {self} !!'. format (name = 'tom', self = 'sir')) # key by filling l=['tom', 'sir'] print ( 'hello, {l [0]}, my name is {l [1]} !!'. format (l = l)) # by filling the array index m={'name': 'tom', 'self': 'sir'} print ( 'hello, {m [name]}, my name is {m [self]} !!'. format (m = m)) # key by filling the dictionary, key without quotes
The above results are output: hello, tom, my name is sir !!
0x02: String sensitive issues
English case conversion on the issue of string can be achieved by following a few functions
# Capitalized a = 'hello,zHong yUan GoNg!!' print(a.title()) # ALL CAPS print(a.upper()) # All lowercase print(a.lower()) The first letter of the first word capitalized # print(a.capitalize())
The output for the first time:
The Hello, Zhong Yuan Gong !!
HELLO, ZHONG YUAN GONG !!
the Hello, zhong Yuan Gong !!
the Hello, zhong Yuan Gong !!
0x03: String slices
d = '123456789' # Get the first 3-6 characters print (d [2: 6]) # entered here is the index of the string, the slicing Python, the former containing the free, as output here is the index of the substring 2-5, rather than under standard substring 2-6. # Get the last two characters print(d[-2:]) # Reverse the string print(d[::-1])
Output:
3456
89
987654321
0x04: Delete spaces in the string
c = ' hello world !!! ' # Remove the string at the beginning and end of the space print(c.strip()) # Remove the strings of spaces left print(c.lstrip()) # Remove spaces to the right of the string print(c.rstrip()) # String remove all spaces print(c.replace(' ',''))
Output as follows:
hello world !!!
hello world !!!
hello world !!!
helloworld!!!
Note: This function is not to strip and split functions confused, the former is to delete the specified character string, the default is a space, which is divided with a specified character string, the default is a space
0x05: change the string encoding
Sometimes we conduct file storage is garbled, this time, we change it encodes OK. Follows
# Convert string encoding e = 'hello, zhongyuan university, you are well! ' print(e.encode('utf-8'))