Table of Contents
1. Slicing
2. strip ()
3. lstrip()
4, rstrip()
5. removeprefix()
6. removesuffix()
7. replace()
8. re.sub()
9. split()
10. rsplit()
11. join()
12. upper()
13. lower()
14. capitalize()
15. islower()
16. isupper()
17, isalpha()
18, isnumeric()
19, isalnum()
20, count()
21. find()
22. rfind()
23, startswith()
24, endswith()
25. partition()
26, center()
27, ljust()
28, rjust()
29, f-Strings
30、swapcase()
31、zfill()
Home Backend Development Python Tutorial 31 essential Python string methods, recommended to collect!

31 essential Python string methods, recommended to collect!

Apr 12, 2023 pm 02:52 PM
python string

31 essential Python string methods, recommended to collect!

String is the basic data type in Python, and it is used in almost every Python program.

1. Slicing

slicing, taking out some elements from a list or tuple according to certain conditions (such as a specific range, index, split value)

s = ' hello '
s = s[:]
print(s)
#hello
s = ' hello '
s = s[3:8]
print(s)
# hello

Copy after login

2. strip ()

strip() method is used to remove specified characters (default is space or newline character) or character sequence at the beginning and end of a string.

s = ' hello '.strip()
print(s)
# hello
s = '###hello###'.strip()
print(s)
# ###hello###

Copy after login

When using the strip() method, spaces or newlines are removed by default, so the # sign is not removed.

You can add specified characters to the strip() method, as shown below.

s = '###hello###'.strip('#')
print(s)
# hello

Copy after login

In addition, when the specified content is not at the beginning and end, it will not be removed.

s = ' n t hellon'.strip('n')
print(s)
#
#hello
s = 'n t hellon'.strip('n')
print(s)
#hello

Copy after login

There is a space before the first n, so only the trailing newline character will be taken.

The last parameter of the strip() method is to strip all combinations of its values. You can see the following case.

s = 'www.baidu.com'.strip('cmow.')
print(s)
# baidu

Copy after login

The outermost first character and last character parameter values ​​will be stripped from the string. Characters are removed from the front until a string character is reached that is not contained in the character set.

A similar action will occur at the tail.

3. lstrip()

Remove the specified character (default is space or newline character) or character sequence on the left side of the string.

s = ' hello '.lstrip()
print(s)
# hello

Copy after login

Similarly, all strings contained in the character set on the left can be removed.

s = 'Arthur: three!'.lstrip('Arthur: ')
print(s)
# ee!

Copy after login

4, rstrip()

Remove the specified character (default is space or newline character) or character sequence on the right side of the string.

s = ' hello '.rstrip()
print(s)
#hello

Copy after login

5. removeprefix()

Function to remove prefix in Python3.9.

# python 3.9
s = 'Arthur: three!'.removeprefix('Arthur: ')
print(s)
# three!

Copy after login

Compared with strip(), the strings in the character set will not be matched one by one.

6. removesuffix()

Function to remove suffix in Python3.9.

s = 'HelloPython'.removesuffix('Python')
print(s)
# Hello

Copy after login

7. replace()

Replace the content in the string with the specified content.

s = 'string methods in python'.replace(' ', '-')
print(s)
# string-methods-in-python
s = 'string methods in python'.replace(' ', '')
print(s)
# stringmethodsinpython

Copy after login

8. re.sub()

re is a regular expression, sub is substitute, which means replacement.

re.sub is a relatively complicated replacement.

import re
s = "stringmethods in python"
s2 = s.replace(' ', '-')
print(s2)
# string----methods-in-python
s = "stringmethods in python"
s2 = re.sub("s+", "-", s)
print(s2)
# string-methods-in-python

Copy after login

Compared with replace(), using re.sub() for replacement operation is indeed more advanced.

9. split()

Split the string, and the final result is a list.

s = 'string methods in python'.split()
print(s)
# ['string', 'methods', 'in', 'python']

Copy after login

When the delimiter is not specified, it will be separated by spaces by default.

s = 'string methods in python'.split(',')
print(s)
# ['string methods in python']

Copy after login

In addition, you can also specify the number of times the string is separated.

s = 'string methods in python'.split(' ', maxsplit=1)
print(s)
# ['string', 'methods in python']

Copy after login

10. rsplit()

Separate the string starting from the right side.

s = 'string methods in python'.rsplit(' ', maxsplit=1)
print(s)
# ['string methods in', 'python']

Copy after login

11. join()

string.join(seq). Using string as the separator, combine all elements (string representations) in seq into a new string.

list_of_strings = ['string', 'methods', 'in', 'python']
s = '-'.join(list_of_strings)
print(s)
# string-methods-in-python
list_of_strings = ['string', 'methods', 'in', 'python']
s = ' '.join(list_of_strings)
print(s)
# string methods in python

Copy after login

12. upper()

Convert all letters in the string to uppercase.

s = 'simple is better than complex'.upper()
print(s)
# SIMPLE IS BETTER THAN COMPLEX

Copy after login

13. lower()

Convert all letters in the string to lowercase.

s = 'SIMPLE IS BETTER THAN COMPLEX'.lower()
print(s)
# simple is better than complex

Copy after login

14. capitalize()

Convert the first letter in the string to uppercase.

s = 'simple is better than complex'.capitalize()
print(s)
# Simple is better than complex

Copy after login

15. islower()

Determine whether all letters in the string are lowercase, if so, return True, otherwise return False.

print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False
print('simple is better than complex'.islower()) # True

Copy after login

16. isupper()

Determine whether all letters in the string are uppercase, if so, return True, otherwise return False.

print('SIMPLE IS BETTER THAN COMPLEX'.isupper()) # True
print('SIMPLE IS BETTER THAN complex'.isupper()) # False

Copy after login

17, isalpha()

If the string has at least one character and all characters are letters, return True, otherwise return False.

s = 'python'
print(s.isalpha())
# True
s = '123'
print(s.isalpha())
# False
s = 'python123'
print(s.isalpha())
# False
s = 'python-123'
print(s.isalpha())
# False

Copy after login

18, isnumeric()

If the string contains only numeric characters, return True, otherwise return False.

s = 'python'
print(s.isnumeric())
# False
s = '123'
print(s.isnumeric())
# True
s = 'python123'
print(s.isnumeric())
# False
s = 'python-123'
print(s.isnumeric())
# False

Copy after login

19, isalnum()

If there is at least one character in the string and all characters are letters or numbers, return True, otherwise return False.

s = 'python'
print(s.isalnum())
# True
s = '123'
print(s.isalnum())
# True
s = 'python123'
print(s.isalnum())
# True
s = 'python-123'
print(s.isalnum())
# False

Copy after login

20, count()

Returns the number of times the specified content appears in the string.

n = 'hello world'.count('o')
print(n)
# 2
n = 'hello world'.count('oo')
print(n)
# 0

Copy after login

21. find()

Check whether the specified content is included in the string. If so, return the starting index value, otherwise return -1.

s = 'Machine Learning'
idx = s.find('a')
print(idx)
print(s[idx:])
# 1
# achine Learning
s = 'Machine Learning'
idx = s.find('aa')
print(idx)
print(s[idx:])
# -1
# g

Copy after login

In addition, you can also specify the starting range.

s = 'Machine Learning'
idx = s.find('a', 2)
print(idx)
print(s[idx:])
# 10
# arning

Copy after login

22. rfind()

Similar to the find() function, returns the last occurrence of the string, or -1 if there is no match.

s = 'Machine Learning'
idx = s.rfind('a')
print(idx)
print(s[idx:])
# 10
# arning

Copy after login

23, startswith()

Check whether the string starts with the specified content, if so, return True, otherwise return False.

print('Patrick'.startswith('P'))
# True

Copy after login

24, endswith()

Check whether the string ends with the specified content, if so, return True, otherwise return False.

print('Patrick'.endswith('ck'))
# True

Copy after login

25. partition()

string.partition(str), a bit like a combination of find() and split().

Starting from the first position where str appears, divide the string string into a 3-element tuple (string_pre_str, str, string_post_str). If string does not contain str, then string_pre_str==string.

s = 'Python is awesome!'
parts = s.partition('is')
print(parts)
# ('Python ', 'is', ' awesome!')
s = 'Python is awesome!'
parts = s.partition('was')
print(parts)
# ('Python is awesome!', '', '')

Copy after login

26, center()

Returns a new string in which the original string is centered and filled with spaces to the length width.

s = 'Python is awesome!'
s = s.center(30, '-')
print(s)
# ------Python is awesome!------

Copy after login

27, ljust()

Returns a new string in which the original string is left-aligned and padded with spaces to length width.

s = 'Python is awesome!'
s = s.ljust(30, '-')
print(s)
# Python is awesome!------------

Copy after login

28, rjust()

Returns a new string with the original string right-aligned and padded with spaces to the length width.

s = 'Python is awesome!'
s = s.rjust(30, '-')
print(s)
# ------------Python is awesome!

Copy after login

29, f-Strings

f-string is the new syntax for formatting strings.

与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快!

num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
print(s)
# Python is the number 1 in programming!
num = 1
language = 'Python'
s = f'{language} is the number {num*8} in programming!'
print(s)
# Python is the number 8 in programming!

Copy after login

30、swapcase()

翻转字符串中的字母大小写。

s = 'HELLO world'
s = s.swapcase()
print(s)
# hello WORLD

Copy after login

31、zfill()

string.zfill(width)。

返回长度为width的字符串,原字符串string右对齐,前面填充0。

s = '42'.zfill(5)
print(s)
# 00042
s = '-42'.zfill(5)
print(s)
# -0042
s = '+42'.zfill(5)
print(s)
# +0042

Copy after login


The above is the detailed content of 31 essential Python string methods, recommended to collect!. For more information, please follow other related articles on the PHP Chinese website!

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

What is the function of C language sum? What is the function of C language sum? Apr 03, 2025 pm 02:21 PM

There is no built-in sum function in C language, so it needs to be written by yourself. Sum can be achieved by traversing the array and accumulating elements: Loop version: Sum is calculated using for loop and array length. Pointer version: Use pointers to point to array elements, and efficient summing is achieved through self-increment pointers. Dynamically allocate array version: Dynamically allocate arrays and manage memory yourself, ensuring that allocated memory is freed to prevent memory leaks.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Does H5 page production require continuous maintenance? Does H5 page production require continuous maintenance? Apr 05, 2025 pm 11:27 PM

The H5 page needs to be maintained continuously, because of factors such as code vulnerabilities, browser compatibility, performance optimization, security updates and user experience improvements. Effective maintenance methods include establishing a complete testing system, using version control tools, regularly monitoring page performance, collecting user feedback and formulating maintenance plans.

Is distinctIdistinguish related? Is distinctIdistinguish related? Apr 03, 2025 pm 10:30 PM

Although distinct and distinct are related to distinction, they are used differently: distinct (adjective) describes the uniqueness of things themselves and is used to emphasize differences between things; distinct (verb) represents the distinction behavior or ability, and is used to describe the discrimination process. In programming, distinct is often used to represent the uniqueness of elements in a collection, such as deduplication operations; distinct is reflected in the design of algorithms or functions, such as distinguishing odd and even numbers. When optimizing, the distinct operation should select the appropriate algorithm and data structure, while the distinct operation should optimize the distinction between logical efficiency and pay attention to writing clear and readable code.

How to understand !x in C? How to understand !x in C? Apr 03, 2025 pm 02:33 PM

!x Understanding !x is a logical non-operator in C language. It booleans the value of x, that is, true changes to false, false changes to true. But be aware that truth and falsehood in C are represented by numerical values ​​rather than boolean types, non-zero is regarded as true, and only 0 is regarded as false. Therefore, !x deals with negative numbers the same as positive numbers and is considered true.

What does sum mean in C language? What does sum mean in C language? Apr 03, 2025 pm 02:36 PM

There is no built-in sum function in C for sum, but it can be implemented by: using a loop to accumulate elements one by one; using a pointer to access and accumulate elements one by one; for large data volumes, consider parallel calculations.

How to obtain real-time application and viewer data on the 58.com work page? How to obtain real-time application and viewer data on the 58.com work page? Apr 05, 2025 am 08:06 AM

How to obtain dynamic data of 58.com work page while crawling? When crawling a work page of 58.com using crawler tools, you may encounter this...

Copy and paste Love code Copy and paste Love code for free Copy and paste Love code Copy and paste Love code for free Apr 04, 2025 am 06:48 AM

Copying and pasting the code is not impossible, but it should be treated with caution. Dependencies such as environment, libraries, versions, etc. in the code may not match the current project, resulting in errors or unpredictable results. Be sure to ensure the context is consistent, including file paths, dependent libraries, and Python versions. Additionally, when copying and pasting the code for a specific library, you may need to install the library and its dependencies. Common errors include path errors, version conflicts, and inconsistent code styles. Performance optimization needs to be redesigned or refactored according to the original purpose and constraints of the code. It is crucial to understand and debug copied code, and do not copy and paste blindly.

See all articles