String Function
String Function
Slicing
With slicing we can access substrings. It can get optional start and stop indices.
s = ' hello '
s = s[3:8] # no crash if s[3:20]
# 'hello'
strip()
Return a copy of the string with the leading and trailing characters removed. The
chars argument is a string specifying the set of characters to be removed. If omitted
or None, the chars argument defaults to removing whitespace.
s = ' hello '.strip()
# 'hello'
s = '\n\n \t hello\n'.strip('\n')
# ' \t hello'
strip() with combination of characters
s = 'HelloPython'.removesuffix('Python')
# 'Hello'
replace()
Return a copy of the string with all occurrences of substring old replaced by new.
s = ' \n \t hello\n'.replace('\n', '')
# ' \t hello'
8. re.sub()
If we want to replace a specific pattern with another character, we can use
the re module and use a regular expression.
import re
s = "string methods in python"
s2 = re.sub("\s+" , "-", s)
# 'string-methods-in-python'
split()
Return a list of the words in the string, using sep as the delimiter string. If maxsplit
is given, at most maxsplit splits are done.
s = 'string methods in python'.split()
# ['string', 'methods', 'in', 'python']
join()
Return a string which is the concatenation of the strings in iterable.
list_of_strings = ['string', 'methods', 'in', 'python']
s = ' '.join(list_of_strings)
# 'string methods in python'
s = 'PYTHON IS AWESOME!'.lower()
# 'python is awesome!'
s = 'python is awesome!'.capitalize()
# 'Python is awesome!'
islower(), isupper()
Checks if the string consist only of upper or lower characters.
'PYTHON IS AWESOME!'.islower() # False
'python is awesome!'.islower() # True
isalnum(): Return True if all characters in the string are alphanumeric and there is
at least one character, False otherwise.
s = 'python'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# True False True
s = 'python123'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# False False True
s = 'python-123'
print(s.isalpha(), s.isnumeric(), s.isalnum() )
# False False False
count()
Return the number of non-overlapping occurrences of substring sub in the range
[start, end].
n = 'hello world'.count('o')
find()
Return the lowest index in the string where substring sub is found within the slice
s[start:end].
s = 'Machine Learning'
idx = s.find('a')
print(idx) # 1
print(s[idx:]) # 'achine Learning'
idx = s.find('a', 2)
print(idx) # 10
print(s[idx:]) # 'arning'
rfind()
Return the highest index in the string where substring sub is found, such that sub is
contained within s[start:end].
s = 'Machine Learning'
idx = s.rfind('a')
print(idx) #
parts = s.partition('was')
# ('Python is awesome!', '', '')
ljust(): Return the string left justified in a string of length width. Padding is done
using the specified fillchar (default is a space).
rjust(): Return the string right justified in a string of length width. Padding is done
using the specified fillchar (default is a space).
s = 'Python is awesome!'
s = s.center(30, '-')
# ------Python is awesome!------
s = 'Python is awesome!'
s = s.ljust(30, '-')
# Python is awesome!------------
s = 'Python is awesome!'
s = s.rjust(30, '-')
# ------------Python is awesome!
f-Strings
Since Python 3.6, f-strings can be used to format strings. They are more readable,
more concise, and also faster!
num = 1
language = 'Python'
s = f'{language} is the number {num} in programming!'
# 'Python is the number 1 in programming!'
30. swapcase()
Return a copy of the string with uppercase characters converted to lowercase and
vice versa.
s = 'HELLO world'
s = s.swapcase()
# 'hello WORLD'
zfill()
Return a copy of the string left filled with ‚0‘ digits to make a string of length
width. A leading sign prefix (‚+‘/'-') is handled by inserting the padding after the
sign character rather than before.
s = '42'.zfill(5)
# '00042'
s = '-42'.zfill(5)
# '-0042'