In this material, let’s explore the most used ones. It is important to note here that all string methods always return new values, not change the original string.
Table of Contents
1. Aligning a string to the center
The center()
method aligns a string to the center. The alignment is performed at the expense of a certain character (by default, it’s a space). The syntax is str.center(length, fillchar), where:
- length – the length of the string (mandatory);
- fillchar – the character that defines the alignment (optional);
Example code
sentence = 'algorithm'
sentence.center(14,'-')
'---algorithm---'
2. How many times the character occurs in the string
The count()
method returns how many times a particular value occurs in the string. The syntax is str.count(value, start, end), where:
- value – substring which should be searched in the string (obligatory);
- start – start index of the string, where the search should start (optional);
- end – the end index of the string, where the search for the value should end (optional);
Example code
sentence = 'She sells seashells by the sea. The goods she sells are certainly seashells.'
sentence.count('shells')
sentence.count('seashells',9,25)
2
1
3. Search for a substring in a string
find()
method returns the smallest index of the position where the specified substring occurs in the string. If it is not found, it returns -1
.Syntax str.find(value, start, end), where:
- value – substring to be searched in the string (mandatory);
- start – the start index of the string, where the search should start from (optional);
- end – the end index of the string, where the search for the value should end (optional);
Types
rfind()
– Therfind()
method is similar tofind()
, but it returns the largest index.
Example code
sentence = 'She sells seashells by the sea. The goods she sells are definitely seashells.'
sentence.find('shells')
sentence.find('shells',0,9)
sentence.find('p',5,10)
sentence.rfind('shells')
10
-1
8
69
4. Mirroring the case of a string
swapcase()
method returns a copy of the string, where all letters in lower case are written in upper case and vice versa.Syntax string.swapcase() Example code
sentence = 'Queue is another FUNDAMENTAL data structure'
sentence.swapcase()
'qUEUE IS ONE MORE FUNDAMENTAL DATA STRUCTURE'
5. Search at the beginning or at the end of string
The startswith()
method returns True
if the string starts with the given value; otherwise it returns False
. The endswith()
method returns False
if the string ends with a particular value; otherwise – False
. Syntax string.startswith(value, start, end) string.endsswith(value, start, end)
- value is the value to look for in the string (mandatory);
- start is the start index of the string where you want to start the search (optional);
- end – the end index of the string, where the search for the value should end (optional);
Example code
#string.startswith()
sentence = 'Binary search - the classic recursive algorithm'
sentence.startswith("Binary")
sentence.startswith("search",7,20)
True
True
#string.endswith()
sentence.endswith('classic')
False
6. Turning a string into a list
The split()
method returns a list of string words, with space as the default delimiter. Syntax string.split(sep, maxsplit)
- sep is a separator used to separate strings. If nothing is specified, it is a space (optional);
- maxsplit() – indicates the number of separations. The default value (-1) means “in all cases” (optional);
Types
rsplit()
– splits the string starting from the right side.
Example code
#string.split()
fruits = 'apples, mangoes, bananas, grapes'
fruits.split()
fruits.split(",",maxsplit = 2)
['apples,', 'mangoes,', 'bananas,', 'grapes']
['apples', 'mangoes', 'bananas, grapes']
#string.rsplit()
fruits.rsplit(",",maxsplit = 1)
['apples, mangoes, bananas', ' grapes']
7. Changing the case of a string
7.1. first character to uppercase
The capitalize()
method capitalizes only the first character of the string. Syntax string.capitalize()
'san francisco'.capitalize()
'san francisco'
7.2. upper case all characters
The method upper()
makes all characters of the string upper case. The syntax is string.upper()
"san francisco".upper()
'SAN FRANCISCO'
7.all first letters of the words to upper case
The title()
method capitalizes all the first letters in words of a given string. Syntax string.title()
"san francisco."title()
'San Francisco'
8. Left or right alignment of lines
The ljust()
method returns a left-aligned string with a specified character (space by default). The rjust()
method aligns the string to the right edge. Syntax string.rjust/ljust(length, character)
- length – length of the string to be returned (mandatory);
- character – character used to fill the empty space, space by default (optional);
Example code
#str.rjust
text = 'Binary search - '
print(text.rjust(25),'classical recursive algorithm')
Binary search - the classical recursive algorithm
#str.ljust
text = 'Binary search - '
print(text.ljust(25),'classical recursive algorithm')
Binary search - the classical recursive algorithm
9. Removing spaces around a string
The strip()
method returns a copy of the string with certain characters at the beginning and end of the string removed. Space is the default character. The syntax is string.strip(character) Types
rstrip()
– removes characters from the right side of the string.lstrip()
– removes characters from the left side of the string.
Example
#str.strip
string = '#.......Section 3.2.1 Question #32......'
string.strip('.#!')
'Section 3.2.1 Question #32'
#str.rstrip
string.rstrip('.#!')
string.lstrip('.#!')
'#.......Section 3.2.1 Question #32'
'Section 3.2.1 Question #32......'
10. Adding zeros at the beginning of a line
The zfill()
method adds zeros (0) at the beginning of the string. The length of the returned string depends on the specified width. Syntax string.zfill(width)
- the width determines the length of the string to be returned. Zeros are not added if the width parameter is less than the length of the original string.
Example
'7'.zfill(3)
'-21'.zfill(5)
'Python'.zfill(10)
'Python'.zfill(3)
'007'
'-0021'
'0000Python'
'Python'
Outputs
These are just some of the useful string methods built into Python. There are others that are just as important. The article Strings in python 3: Methods, Functions, Formatting is a great resource for delving into all the details.