Home > Article > Backend Development > Python’s built-in string method analysis
This article mainly introduces some of Python’s built-in string methods, including overview, string case conversion, string format output, string search, positioning and replacement, string union and division, and string conditions. Judgment, string encoding
String processing is a very common skill, but Python has too many built-in string methods, which are often forgotten. For quick reference, each built-in method is specially written based on Python 3.5.1 Examples are categorized for easy indexing.
PS: You can click on the green title in the overview to enter the corresponding category or quickly index the corresponding method through the article directory on the right sidebar.
Case conversion
str.capitalize()
Convert the first letter to uppercase , it should be noted that if the first word is not in capital form, the original string will be returned.
'adi dog'.capitalize()
# 'Adi dog'
'abcd Xu'.capitalize()
# 'Abcd Xu'
'Xu abcd'.capitalize()
# 'Xu abcd'
'ß'.capitalize()
# 'SS'
str. lower()
#Convert the string to lowercase, which is only valid for ASCII-encoded letters.
'DOBI'.lower()
# 'dobi'
'ß'.lower() # 'ß' is a German lowercase letter, which has another lowercase 'ss' ', lower method cannot be converted
# 'ß'
'Xu ABCD'.lower()
# 'Xu abcd'
##str.casefold ()
# 'dobi'
# 'ss'
str.swapcase()
#: 'Xu dOBI A123 SS' The ß here is converted to SS, which is a kind of capital
But it should be noted that s.swapcase( ).swapcase() == s may not be true:
# 'µ'
# 'Μ'
# 'μ'
Out[154]: '0x3bc'
str.title()
# 'Hello World'
# 'Chinese Abc Def 12Gh'
"they're bill's friends from the UK".title()
# "They'Re Bill'S Friends From The Uk"
str.upper()
# 'Chinese ABC DEF 12GH'
It should be noted that s.upper().isupper() is not necessarily True.
String format output
Center the string according to the given width, you can Pads the excess length given a specified number of characters, or returns the original string if the specified length is less than the string length.
# '**12345***'
# ' 12345 '
str.ljust(width[, fillchar]); str.rjust(width[, fillchar])
# 'dobi '
# 'dobi~~~~~ ~'
# 'dobi'
# 'dobi'
str.zfill(width)
# '00042'
"-42".zfill(5)
# '-0042'
# '000dd'
# '-000-'
# '0000 '
# '00000'
# 'dddddddd'
str.expandtabs(tabsize=8)
Replace horizontal tab characters with specified spaces so that the spacing between adjacent strings remains within the specified number of spaces.
tab.expandtabs()
# '1 23 456 7890 1112131415 161718192021'
# '123456781234567812345678123456781234567 812345678' Pay attention to the relationship between the count of spaces and the output position above
tab.expandtabs(4)
# '1 23 456 7890 1112131415 161718192021'
# '12341234123412341234123412341234'
str.format(^args, ^^kwargs)
The syntax of the format string is complicated Many, The official documents already have relatively detailed examples, so I won’t write examples here. Those who want to know more about children’s shoes can directly click here Format examples.
str.format_map(mapping)
Similar to str .format(*args, **kwargs), the difference is that mapping is a dictionary object.
People = {'name':'john', 'age':56}
'My name is {name},i am {age} old'.format_map(People)
# 'My name is john,i am 56 old'
String search, positioning and replacement
str.count(sub[, start[, end] ])
text = 'outer protective covering'
text.count('e')
# 4
text.count('e', 5, 11)
# 1
text.count('e', 5, 10)
# 0
str.find(sub[, start[, end]]); str.rfind(sub [, start[, end]])
text = 'outer protective covering'
text.find('er')
# 3
text.find('to ')
# -1
text.find('er', 3)
Out[121]: 3
text.find('er', 4)
Out[122]: 20
text.find('er', 4, 21)
Out[123]: -1
text.find('er', 4, 22)
Out[124]: 20
text.rfind('er')
Out[125]: 20
text.rfind('er', 20)
Out[126]: 20
text.rfind('er', 20, 21)
Out[129]: -1
str.index(sub[, start [, end]]); str.rindex(sub[, start[, end]])
Similar to find() rfind(), except that if it is not found, a ValueError will be raised.
str.replace(old, new[, count])
'dog wow wow jiao'.replace('wow', 'wang')
# 'dog wang wang jiao'
'dog wow wow jiao'.replace('wow', 'wang', 1)
# 'dog wang wow jiao'
'dog wow wow jiao'.replace('wow ', 'wang', 0)
# 'dog wow wow jiao'
'dog wow wow jiao'.replace('wow', 'wang', 2)
# 'dog wang wang jiao'
'dog wow wow jiao'.replace('wow', 'wang', 3)
# 'dog wang wang jiao'
str.lstrip([chars]); str.rstrip([chars]); str.strip([chars])
' dobi'.lstrip()
# 'dobi'
'db.kun.ac.cn'.lstrip(' dbk')
# '.kun.ac.cn'
' dobi '.rstrip()
# ' dobi'
'db.kun.ac.cn'.rstrip( 'acn')
# 'db.kun.ac.'
' dobi '.strip()
# 'dobi'
'db.kun.ac.cn'.strip ('db.c')
# 'kun.ac.cn'
'db.kun.ac.cn'.strip('cbd.un')
# 'kun.a'
static str.maketrans(x[, y[, z]]); str.translate(table)
maktrans is a static method used to generate a comparison table for use by translate.
If maktrans has only one parameter, the parameter must be a dictionary. The key of the dictionary is either a Unicode encoding (an integer) or a string of length 1. The value of the dictionary can be any string. None or Unicode encoding.
a = 'dobi'
ord('o')
# 111
ord('a')
# 97
hex( ord('dog'))
# '0x72d7'
b = {'d':'dobi', 111:' is ', 'b':97, 'i':'\u72d7 \u72d7'}
table = str.maketrans(b)
a.translate(table)
# 'dobi is a dog'
If maktrans has Two parameters, then the two parameters form a mapping, and the two strings must be of equal length; if there is a third parameter, the third parameter must also be a string, and the string will be automatically mapped to None:
a = 'dobi is a dog'
table = str.maketrans('dobi', 'alph')
a.translate(table)
# 'alph hs a alg'
table = str.maketrans('dobi', 'alph', 'o')
a.translate(table)
# 'aph hs a ag'
Union and split of strings
##str.join(iterable)
# '2012-3-12'
# TypeError: sequence item 0: expected str instance, int found
# TypeError: sequence item 2: expected str instance, bytes found
'-'.join(['2012'])
# '2012'
'-'.join([])
# ''
'-'.join([None])
# TypeError: sequence item 0: expected str instance, NoneType found
'-'.join([''])
# ''
','.join({'dobi':'dog', 'polly':'bird'})
# 'dobi,polly'
','.join({'dobi':'dog', 'polly':'bird'}.values())
# 'dog,bird'
str.partition(sep); str.rpartition(sep)
'dog wow wow jiao'.partition('wow')
# ('dog ', 'wow', ' wow jiao')
'dog wow wow jiao'.partition('dog')
# ('', 'dog', ' wow wow jiao')
'dog wow wow jiao'.partition('jiao')
# ('dog wow wow ', 'jiao', '')
'dog wow wow jiao'.partition('ww')
# ('dog wow wow jiao', '', '')
'dog wow wow jiao'.rpartition('wow')
Out[131]: ('dog wow ', 'wow', ' jiao')
'dog wow wow jiao'.rpartition('dog')
Out[132]: ('', 'dog', ' wow wow jiao')
'dog wow wow jiao'.rpartition('jiao')
Out[133]: ('dog wow wow ', 'jiao', '')
'dog wow wow jiao'.rpartition('ww')
Out[135]: ('', '', 'dog wow wow jiao')
str.split(sep=None, maxsplit=-1); str.rsplit(sep=None, maxsplit=-1)
'1,2,3'.split(','), '1, 2, 3'.rsplit()
# (['1', '2', '3'], ['1,', '2,', '3'])
'1,2,3'.split(',', maxsplit=1), '1,2,3'.rsplit(',', maxsplit=1)
# (['1', '2,3'], ['1,2', '3'])
'1 2 3'.split(), '1 2 3'.rsplit()
# (['1', '2', '3'], ['1', '2', '3'])
'1 2 3'.split(maxsplit=1), '1 2 3'.rsplit(maxsplit=1)
# (['1', '2 3'], ['1 2', '3'])
' 1 2 3 '.split()
# ['1', '2', '3']
'1,2,,3,'.split(','), '1,2,,3,'.rsplit(',')
# (['1', '2', '', '3', ''], ['1', '2', '', '3', ''])
''.split()
# []
''.split('a')
# ['']
'bcd'.split('a')
# ['bcd']
'bcd'.split(None)
# ['bcd']
str.splitlines([keepends])
字符串以行界符为分隔符拆分为列表;当 keepends 为True,拆分后保留行界符,能被识别的行界符见官方文档。
'ab c\n\nde fg\rkl\r\n'.splitlines()
# ['ab c', '', 'de fg', 'kl']
'ab c\n\nde fg\rkl\r\n'.splitlines(keepends=True)
# ['ab c\n', '\n', 'de fg\r', 'kl\r\n']
"".splitlines(), ''.split('\n') #注意两者的区别
# ([], [''])
"One line\n".splitlines()
# (['One line'], ['Two lines', ''])
字符串条件判断
str.endswith(suffix[, start[, end]]); str.startswith(prefix[, start[, end]])
text = 'outer protective covering'
text.endswith('ing')
# True
text.endswith(('gin', 'ing'))
# True
text.endswith('ter', 2, 5)
# True
text.endswith('ter', 2, 4)
# False
str.isalnum()
字符串和数字的任意组合,即为真,简而言之:
只要 c.isalpha(), c.isdecimal(), c.isdigit(), c.isnumeric() 中任意一个为真,则 c.isalnum() 为真。
'dobi'.isalnum()
# True
'dobi123'.isalnum()
# True
'123'.isalnum()
# True
'徐'.isalnum()
# True
'dobi_123'.isalnum()
# False
'dobi 123'.isalnum()
# False
'%'.isalnum()
# False
str.isalpha()
Unicode 字符数据库中作为 “Letter”(这些字符一般具有 “Lm”, “Lt”, “Lu”, “Ll”, or “Lo” 等标识,不同于 Alphabetic) 的,均为真。
'dobi'.isalpha()
# True
'do bi'.isalpha()
# False
'dobi123'.isalpha()
# False
'徐'.isalpha()
# True
str.isdecimal(); str.isdigit(); str.isnumeric()
三个方法的区别在于对 Unicode 通用标识的真值判断范围不同:
isdecimal: Nd,
isdigit: No, Nd,
isnumeric: No, Nd, Nl
The difference between digit and decimal is that some numerical strings are digit but not decimal. Click here for details
num = '\u2155'
print(num)
# ⅕
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, False, True)
num = '\u00B2'
print(num)
# ²
num.isdecimal(), num.isdigit(), num.isnumeric()
# (False, True, True)
num = "1" #unicode
num .isdecimal(), num.isdigit(), num.isnumeric()
# (Ture, True, True)
num = "'Ⅶ'"
num.isdecimal(), num .isdigit(), num.isnumeric()
# (False, False, True)
num = "十"
num.isdecimal(), num.isdigit(), num.isnumeric ()
# (False, False, True)
num = b"1" # byte
num.isdigit() # True
num.isdecimal() # AttributeError 'bytes' object has no attribute 'isdecimal'
num.isnumeric() # AttributeError 'bytes' object has no attribute 'isnumeric'
str.isidentifier()
Judge string Whether it can be a legal identifier.
'def'.isidentifier()
# True
'with'.isidentifier()
# True
'false'.isidentifier ()
# True
'dobi_123'.isidentifier()
# True
'dobi 123'.isidentifier()
# False
'123'.isidentifier()
# False
str.islower()
'Xu'.islower()
# False
'ß'.islower() #German Capital letters
# False
'aXu'.islower()
# True
'ss'.islower()
# True
'23'.islower()
# False
'Ab'.islower()
# False
str.isprintable()
Determine whether all characters in the string are printable characters or the string is empty. Characters in the "Other" and "Separator" categories of the Unicode character set are non-printable characters (but do not include ASCII spaces (0x20)).
'dobi123'.isprintable()
# True
'dobi123\n'.isprintable()
Out[24]: False
'dobi 123'.isprintable()
# True
'dobi.123'.isprintable()
# True
''.isprintable()
# True
str.isspace()
Determine whether there is at least one character in the string, and all characters are blank characters.
In [29]: '\r\n\t'.isspace()
Out[29]: True
In [30]: ''.isspace()
Out[30]: False
In [31]: ' '.isspace()
Out[31]: True
str.istitle()
Determine whether the characters in the string are capitalized, and non-alphabetic characters will be ignored.
'How Python Works'.istitle()
# True
'How Python WORKS'.istitle()
# False
'how python works '.istitle()
# False
'How Python Works'.istitle()
# True
' '.istitle()
# False
''.istitle()
# False
'A'.istitle()
# True
'a'.istitle()
# False
'Diaoshui Abc Def 123'.istitle()
# True
str.isupper()
'Xu'.isupper()
# False
'DOBI'.isupper()
Out[41]: True
'Dobi'.isupper()
# False
'DOBI123'.isupper()
# True
'DOBI 123'.isupper()
# True
'DOBI\t 123'.isupper()
# True
' DOBI_123'.isupper()
# True
'_123'.isupper()
# False
##String encoding
# UnicodeEncodeError: 'ascii' codec can't encode character '\u5f90'...
# b'?'
# b''
# b'Xu '
# b'\\u5f90'