string python
string python
know
In this article we learn about the most essential built-in string methods.
Patrick Loeber · · · · ·
December 19, 2021 · 14 min read
Python Basics
Strings are an essential data type in Python that are used in nearly every application. In this article
we learn about the most essential built-in string methods.
With this resource you will be equipped with all the tips and knowledge you need to work with
strings easily and you will be able to modify them without any problems.
1. Slicing
With slicing we can access substrings. It can get optional start and stop indices.
2. 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 \t hello\n'.strip('\n')
# -> not leading, so the first \n is not removed!
# ' \n \t hello'
s = '\n\n \t hello\n'.strip('\n')
# ' \t hello'
strip() with combination of characters
The chars argument is a string specifying the set of characters to be removed. So all occurrences
of these characters are removed, and not the particular given string.
s = 'www.example.com'.strip('cmow.')
# 'example'
s = 'HelloPython'.removesuffix('Python')
# 'Hello'
7. replace()
Return a copy of the string with all occurrences of substring old replaced by new.
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'
10. rsplit()
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, the rightmost ones.
11. join()
Return a string which is the concatenation of the strings in iterable.
s = 'python is awesome!'.upper()
# 'PYTHON IS AWESOME!'
s = 'PYTHON IS AWESOME!'.lower()
# 'python is awesome!'
s = 'python is awesome!'.capitalize()
# 'Python is awesome!'
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
20. count()
Return the number of non-overlapping occurrences of substring sub in the range [start, end].
n = 'hello world'.count('o')
# 2
21. 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'
22. 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) # 10
25. partition()
Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the
separator, the separator itself, and the part after the separator. If the separator is not found, return
a 3-tuple containing the string itself, followed by two empty strings.
s = 'Python is awesome!'
parts = s.partition('is')
# ('Python ', 'is', ' awesome!')
parts = s.partition('was')
# ('Python is awesome!', '', '')
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!
29. 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'
31. 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'
More on Strings
More information about Strings in Python can be found in this article: Strings - Advanced Python
05.
you! 🙏