Home Backend Development Python Tutorial Python's built-in string method analysis

Python's built-in string method analysis

Mar 07, 2017 pm 03:48 PM
python String methods

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 ()

Convert the string to lowercase. Any corresponding lowercase form in Unicode encoding will be converted.

'DOBI'.casefold()

# 'dobi'

'ß'.casefold() #The lowercase letter ß in German is equivalent to the lowercase letter ss, and its capital is SS

# 'ss'

str.swapcase()

Reverse the case of string letters.

'Xu Dobi a123 ß'.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:

u'\xb5'

# 'µ'

u'\xb5'.swapcase()

# 'Μ'

u'\xb5'.swapcase().swapcase()

# 'μ'

hex(ord(u'\xb5'.swapcase().swapcase ()))

Out[154]: '0x3bc'

The lower case of 'Μ' (is mu, not M) is exactly the same as the writing of 'μ'.

str.title()

Capitalize the first letter of each "word" in the string. The basis for judging "words" is based on spaces and punctuation, so when you write English possessives or some English capital abbreviations, you will make mistakes.

'Hello world'.title()

# 'Hello World'

'Chinese abc def 12gh'.title()

# 'Chinese Abc Def 12Gh'

# But this method is not perfect:

"they're bill's friends from the UK".title()
# "They'Re Bill'S Friends From The Uk"

str.upper()

Changes all letters in the string to uppercase and will automatically ignore characters that cannot be converted to uppercase.

'Chinese abc def 12gh'.upper()

# 'Chinese ABC DEF 12GH'
It should be noted that s.upper().isupper() is not necessarily True.

String format output

str.center(width[, fillchar])

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'.center(10, '*')

# '**12345***'

'12345'.center(10)

# ' 12345 '
str.ljust(width[, fillchar]); str.rjust(width[, fillchar])

Returns a string of specified length, the content of the string is on the left (right) if the length If it is less than the length of the string, the original string is returned. The default padding is ASCII spaces, and the padded string can be specified.

'dobi'.ljust(10)

# 'dobi '

'dobi'.ljust(10, '~')

# 'dobi~~~~~ ~'

'dobi'.ljust(3, '~')

# 'dobi'

'dobi'.ljust(3)

# 'dobi'
str.zfill(width)

Fills the string with '0' and returns a string with the specified width.

"42".zfill(5)

# '00042'
"-42".zfill(5)
# '-0042'

'dd' .zfill(5)

# '000dd'

'--'.zfill(5)

# '-000-'

' '.zfill(5)

# '0000 '

''.zfill(5)

# '00000'

'dddddddd'.zfill(5)

# '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 = '1\t23\t456\t7890\t1112131415\t161718192021'

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)

Use the specified string to connect iterable objects whose elements are strings.

'-'.join(['2012', '3', '12'])

# '2012-3-12'

'-'.join([ 2012, 3, 12])

# TypeError: sequence item 0: expected str instance, int found

'-'.join(['2012', '3', b'12']) #bytes is not a string

# 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

str.encode(encoding="utf-8", errors="strict")


fname = 'Xu'

fname.encode('ascii ')

# UnicodeEncodeError: 'ascii' codec can't encode character '\u5f90'...

fname.encode('ascii', 'replace')

# b'?'

fname.encode('ascii', 'ignore')

# b''

fname.encode('ascii', 'xmlcharrefreplace')

# b'Xu '

fname.encode('ascii', 'backslashreplace')

# b'\\u5f90'

For more articles related to Python's built-in string method analysis, please pay attention to PHP Chinese net!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles