Learn the 31 ways you need to work with Python strings

Mondo Technology Updated on 2024-01-29

By slicing, we can access substrings.

>>>s = ' hello '

s[3:8]

hello'

Lets you remove the characters specified in the head and end of the string (spaces or line breaks by default).

>>>s = ' hello '

s.strip()

hello'

s = '###hello###

s.strip('#

hello'

s = ' \t hello'

s.strip('')

t hello'

s = ' \t hello'

s.strip('')

t hello'

Not to start, so the left side has not been removed

lstrip([chars]): used to truncate the space on the left side of the string or specify a character.

rtrip([chars]): used to truncate the space on the right side of the string or specify a character.

>>>s = ' hello '

s.lstrip()

hello '

s.rstrip()

hello'

s.lstrip('#

hello###

s.rstrip('#

###hello'

s = 'www.example.com'

s.strip('.wcmo')

example'

If the parameter is a string, then all of these occurring characters will be removed instead of the given string.

As mentioned earlier, strip, lstrip, and rstrip remove all passed parameter strings. So, if we just want to remove the given string, we can use removeprefix and removesuffix.

>>>s = 'arthur: three!'

s.lstrip('arthur: ')

ee!'>> s = 'arthur: three!'

s.removeprefix('arthur: ')

three!'

s = 'arthur: three!'

s.removesuffix('three!')

arthur: '

Replace the old string with new, and if the third parameter max is specified, replace it no more than max times.

>>>s = ' \t hello'

s.replace('', '', 1)

t hello'

If we want to replace a character with a specific pattern, we can use a regular expression.

>>>import re

s = "string methods in python"

s2 = re.sub("\s+" , "-", s)

s2string-methods-in-python'

For more information on regular expressions, refer to the history article.

By specifying a delimiter to slice a string, the method splits the string into substrings and returns a list of those substrings. If the second parameter, num, has a specified value, it is split into num+1 substrings.

>>>s = 'string methods in python'

s.split()

string', 'methods', 'in', 'python']

s = 'string methods in python'

s.split(' ', 2)

string', 'methods', 'in python']

Similar to the split() function, if the second parameter num has a specified value, it is split from the far right.

>>>s = 'string methods in python'

s.rsplit()

string', 'methods', 'in', 'python']

s = 'string methods in python'

s.rsplit(' ', 2)

string methods', 'in', 'python']

Used to concatenate elements in a sequence with a specified character to generate a new string.

>>>lst = ['string', 'methods', 'in', 'python']

s = ' '.join(lst)

sstring methods in python'

Returns a copy of the string, with the function that all uppercase and lowercase characters are converted to uppercase, lowercase, or uppercase for the first character, with the rest lowercase.

>>>s = 'string methods in python'

s.upper()

string methods in python'

s.lower()

string methods in python'

s.capitalize()

string methods in python'

Check if the string consists of only large or small characters.

>>>s = 'string methods in python'

s.islower()

false>> s.isupper()

false>> s = 'string methods in python'

s.islower()

true>> s = 'string methods in python'

s.isupper()

true

isalpha(): Returns true if all characters in the string consist of only letters or literals, false otherwise.

isnumeric(): Returns true if all characters in the string consist of only numbers, and false otherwise.

isalnum(): Returns true if all characters in the string are composed of letters and numbers, false otherwise.

>>>s = 'python'

s.isalpha()

true>> s.isnumeric()

false>> s.isalnum()

true>> s = 'python666'

s.isalpha()

false>> s.isnumeric()

false>> s.isalnum()

true>> s = 'python-666'

s.isalpha()

false>> s.isnumeric()

false>> s.isalnum()

false

It is used to count the number of occurrences of a character in a string. The optional parameters are the start and end locations of the search on strings.

>>>s = 'hello world'

s.count('o')

s.count('o', 0, 5)

Detects if the string contains a substring str, and if so, returns the starting position of the index value in the string. If not, -1 is returned.

>>>s = 'hello world'

s.find('a')

s.find('o')

Returns where the string last occurred, or -1 if there is no match.

>>>s = 'hello world'

s.rfind('o')

Used to check if the string starts and ends with the specified substring, if it returns true, otherwise it returns false.

>>>s = 'hello world'

s.startswith('he')

true>> s.endswith('d')

true

Used to split strings based on a specified delimiter. If no delimiter is found, a tuple containing the string itself is returned, followed by two empty strings.

>>>s = 'python is awesome!'

s.partition('is')

python ', 'is', ' awesome!')

s.partition('iss')

python is awesome!', '', '')

center(): Returns a string centered on the specified width width, optionally a padded character, default is a space.

ljust(): Returns a specified width width, the string is left-aligned, and the optional parameter is a padded character, which is a space by default.

rjust(): Returns a specified width width, string right-aligned, optional parameter is a padded character, default is a space.

>>>s = 'python'

s.center(10, '-')

python--'

s.ljust(10, '-')

python---'

s.rjust(10, '-')

-python'

f-strings can be used to format strings. More readable, more concise, and faster!

>>>num = 1

language = 'python'

s = f' is the number in programming!'

spython is the number 1 in programming!'

Used to convert uppercase and lowercase letters to strings, i.e., convert uppercase letters to lowercase letters, and lowercase letters to uppercase letters.

>>>s = 'hello world'

s.swapcase()

hello world'

31. zfill()

Returns a string of the specified length, the original string is right-aligned, and 0 is padded in front of it. If the string has a prefix ('+'/'-') inserts padding after the prefix character instead of before.

>>>s = '168'

s.zfill(6)

s = '-168'

s.zfill(6)

It's not easy to create an article, if you like this article, please follow, like and share it with your friends. If you have comments and suggestions, please give us feedback in the comments!

Related Pages