31 Necessary Python string methods, recommended collection!

Hello, I'm little F.

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

Today, little F will take you to learn the 31 most important built-in string methods.

I hope you can find helpful skills from it.

▍1,Slicing

slicing slice, which extracts some elements (such as specific range, index and split value) from the list or tuple according to certain conditions

s = '   hello   '
s = s[:]

print(s)
#    hello


s = '   hello   '
s = s[3:8]

print(s)
# hello

▍2,strip()

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

s = '   hello   '.strip()

print(s)
# hello


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

print(s)
# ###hello###

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

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

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

print(s)
# hello

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

s = ' \n \t hello\n'.strip('\n')

print(s)
#
#      hello


s = '\n \t hello\n'.strip('\n')

print(s)
#      hello

The first \ n is preceded by a space, so only the trailing newline character will be taken.

Finally, the parameter of 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

The outermost first and last character parameter values are stripped from the string. The character is removed from the front end until it reaches a string character that is not included in the character set.

A similar action occurs at the tail.

▍3,lstrip()

Removes the specified character (space or newline by default) or character sequence to the left of the string.

s = '   hello   '.lstrip()

print(s)
# hello

Similarly, you can remove all strings contained in the character set on the left.

s = 'Arthur: three!'.lstrip('Arthur: ')

print(s)
# ee!

▍4,rstrip()

Removes the specified character (space or newline by default) or character sequence to the right of the string.

s = '   hello   '.rstrip()

print(s)
#    hello

▍5,removeprefix()

Python3.9 to remove the prefix.

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

print(s)
# three!

Compared with strip(), strings in character set are not matched one by one.

▍6,removesuffix()

Python3.9 to remove the suffix.

s = 'HelloPython'.removesuffix('Python')

print(s)
# Hello

▍7,replace()

Replace the content in the specified string with the content in the specified string.

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

print(s)
# string-methods-in-python


s = 'string methods in python'.replace(' ', '')

print(s)
# stringmethodsinpython

▍8,re.sub()

re is a regular expression, and sub is substitute, indicating substitution.

re.sub is the replacement of relatively complex points.

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


s = "string    methods in python"
s2 = re.sub("\s+", "-", s)
print(s2)
# string-methods-in-python

Compare with replace() and use re Sub() performs the replacement operation, which is indeed more advanced.

▍9,split()

The string is separated, and the final result is a list.

s = 'string methods in python'.split()

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

When no separator is specified, it is separated by spaces by default.

s = 'string methods in python'.split(',')

print(s)
# ['string methods in python']

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

s = 'string methods in python'.split(' ', maxsplit=1)

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

▍10,rsplit()

Separate strings from the right.

s = 'string methods in python'.rsplit(' ', maxsplit=1)

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

▍11,join()

string.join(seq). Take string as the separator to combine all elements (string representation) 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

▍12,upper()

Convert all letters in the string to uppercase.

s = 'simple is better than complex'.upper()

print(s)
# SIMPLE IS BETTER THAN COMPLEX

▍13,lower()

Converts all letters in the string to lowercase.

s = 'SIMPLE IS BETTER THAN COMPLEX'.lower()

print(s)
# simple is better than complex

▍14,capitalize()

Converts the first letter in a string to uppercase.

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

print(s)
# Simple is better than complex

▍15,islower()

Judge whether all letters in the string are lowercase. If yes, it returns True; otherwise, it returns False.

print('SIMPLE IS BETTER THAN COMPLEX'.islower()) # False

print('simple is better than complex'.islower()) # True

▍16,isupper()

Judge whether all letters in the string are capitalized. If yes, it returns True; otherwise, it returns False.

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

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

▍17,isalpha()

Returns True if the string has at least one character and all characters are letters, otherwise returns 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

▍18,isnumeric()

Returns True if the string contains only numeric characters, otherwise 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

▍19,isalnum()

Returns True if there is at least one character in the string and all characters are letters or numbers, otherwise returns 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

▍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

▍21,find()

Detect 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

In addition, you can specify the starting range.

s = 'Machine Learning'
idx = s.find('a', 2)

print(idx)
print(s[idx:])
# 10
# arning

▍22,rfind()

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

s = 'Machine Learning'
idx = s.rfind('a')

print(idx)
print(s[idx:])
# 10
# arning

▍23,startswith()

Check whether the string starts with the specified content. If yes, it returns True; otherwise, it returns False.

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

# True

▍24,endswith()

Check whether the string ends with the specified content. If yes, it returns True; otherwise, it returns False.

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

# True

▍25,partition()

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

From the first position where STR appears, the string is divided into a 3-element tuple (string_pre_str,str,string_post_str). If STR is not included in the string, the 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!', '', '')

▍26,center()

Returns a new string centered on the original string and filled with spaces to the length width.

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

print(s)
# ------Python is awesome!------

▍27,ljust()

Returns a new string that is left aligned with the original string and filled with spaces to the length width.

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

print(s)
# Python is awesome!------------

▍28,rjust()

Returns a new string with the original string right justified and filled with spaces to the length width.

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

print(s)
# ------------Python is awesome!

▍29,f-Strings

f-string is a new syntax for formatting strings.

Compared with other formatting methods, they are not only easier to read, simpler, less error prone, but also faster!

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!

▍30,swapcase()

Flips the case of letters in a string.

s = 'HELLO world'
s = s.swapcase()

print(s)
# hello WORLD

▍31,zfill()

string.zfill(width).

Returns a string with a length of width. The original string is aligned to the right and filled with 0 in front.

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

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

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

Added by chinto09 on Thu, 17 Feb 2022 04:49:51 +0200