Python string commonly used methods and functions

str = 'hello world'

  1. Join merge, use the string before join as the separator to merge the elements in the list into a new string
    str_1='*'.join(['Are','you','ok'])
    print(str_1)
    #结果Are*you*ok
  2. Separate, split separates the string into a list according to the separator, and can also take the parameter num (the number of separations)
    splitlines, separate by line ('\r','\r\n', \n'), and can take the parameter whether to keep the line break Character ('\r','\r\n', \n'), the default is False, does not include the newline character, if it is True, the newline character is retained
    print(str.split())
    #结果['hello', 'world']
    print(str.split('o'))
    #结果['hell', ' w', 'rld']
    print(str.split('o',1))
    #结果['hell', ' world']
    strline='hello\nword'
    print(strline.splitlines(),',',strline.splitlines(True))
    #结果['hello', 'word'] , ['hello\n', 'word']
  3. To determine the beginning and end of the string endwith, startswith
    #3.1endwith判断以什么结尾,参数为1字符串,2开始位置,3结束位置
    print(str.endswith('ld'),str.endswith('l'),str.endswith('o',2,5),str.endswith('l',2,5))
    #结果True False True False
    #3.2startswith判断以什么开始,同理
    print(str.startswith('he'),str.startswith('e'),str.startswith('h',1,4),str.startswith('e',1,4))
    #结果True False False True
  4. IsX judgment of string
    print(str.isalnum(),str.isalpha(),str.isascii(),str.isdecimal(),str.islower())
    #结果False False True False True

    isX description, both return True or Flase
    string.isalnum() if string has at least one character and all characters are letters or numbers
    string.isalpha() if string has at least one character and all characters are letters
    string.isdecimal() If string contains only decimal digits
    string.isdigit() If string contains only digits
    string.islower() If string contains at least one case-sensitive character, and all these (case-sensitive) characters are lowercase
    string.isnumeric( ) If the string contains only numeric characters
    string.isspace() If the string contains only spaces
    string.istitle() If the string is titled (see title(), each word is capitalized)
    string.isupper() If the string contains at least one case-sensitive character, and all these (case-sensitive) characters are uppercase

  5. String case formatting, title title (capitalize the first letter of each word), upper all uppercase, lower all lowercase, capitalize first letter uppercase, swapcase reverse case
    print(str.title(),'**',str.lower(),'**',str.upper(),'**',str.capitalize(),'**',str.swapcase())
    #结果Hello World ** hello world ** HELLO WORLD ** Hello world ** HELLO WORLD
  6. The position alignment format of the string, center is centered, rjust is aligned right, ljust is aligned left, parameter 1 is the alignment position, parameter 2 is aligned character,
    special alignment: zfill returns a string of specified length, and the original string is aligned to the right. Fill 0 in front
    print(str.center(20),',',str.center(20,'*'))
    #结果    hello world     ,****hello world*****
    print(str.rjust(20),',',str.rjust(20,'*'))
    #结果         hello world , *********hello world
    print(str.ljust(20),',',str.ljust(20,'*'))
    #结果hello world          , hello world*********
    print(str.zfill(20))
    #000000000hello world

    print (str.ljust (20), ',', str.ljust (20, '*'))

  7. The deletion of the string is the formatting of the specified characters, strip removes the specified characters at the beginning and the end (default space), srtip removes the right side, and lstrip removes the left side
    str1= '   hello world   '
    print(str1.strip(),',',str.strip('d'))
    #结果hello world , hello worl
    print(str1.rstrip(),',',str.rstrip('d'))
    #结果   hello world , hello worl
    print(str1.lstrip(),',',str.lstrip('h'))
    #结果hello world    , ello world
  8. String search, find, find whether it contains a certain character, can bring start and end position, return index value if found, return -1
    if not found index is the same as find, but if not found, an exception will be reported, or start and End position, rfind and rindex are queried from right to left, and the remaining parameters are the same
    print(str.find('o'),str.find('a'),str.find('o',10,20))
    #结果4 -1 -1
    print(str.index('o'),end=',')
    try:
    print(str.index('a'))
    except:
    print('error')
    #结果4,error
    print(str.rfind('o'),str.rindex('o'))
    #结果7 7
  9. Character replacement, replace replacement characters (all replacement by default, you can specify the number of times), expandtabs can replace tabs with spaces, the value is the number of spaces, the default is 8 (a space equal to tab)
    print(str.replace('o','a'),',',str.replace('o','a',1))
    #结果hella warld , hella world
    strtab='hello\tworld'
    print(strtab,',',strtab.expandtabs(1))
    #结果hello    world , hello world
  10. The partition() method is used to split the string according to the specified separator, like the combination of find() and split(), the returned tuple, rpartition starts from the right
    strwww='www.baidu.com'
    print(strwww.partition('.'),strwww.rpartition('.'))
    #结果('www', '.', 'baidu.com') ('www.baidu', '.', 'com')
  11. format, formatting, similar to %, the format function can accept unlimited parameters, and the positions can be out of order
    
    print("{} {}".format("hello", "world") )
    #结果hello world
    print("{0} {1} {0}".format("hello", "world") )
    #结果hello world hello

Guess you like

Origin blog.51cto.com/xxy12345/2544640