Python String Methods:
- capitalize()
- casefold()
- center()
- count()
- encode()
- endswith()
- expandtabs()
- find()
- format()
- format_map()
- index()
- isalnum()
- isalpha()
- isascii()
- isdecimal()
- isdigit()
- isidentifier()
- islower()
- isnumeric()
- isprintable()
- isspace()
- istitle()
- isupper()
- join()
- ljust()
- lower()
- lstrip()
- maketrans()
- partition()
- removeprefix()
- removesuffix()
- replace()
- rfind()
- rindex()
- rjust()
- rpartition()
- rsplit()
- rstrip()
- split()
- splitlines()
- startswith()
- strip()
- swapcase()
- title()
- translate()
- upper()
- zfill()
1. str.capitalize()
capitalize()
method returns a string
where the first character is upper case, and the rest is lower case.txt = "hello, and welcome to my world." x = txt.capitalize() print (x)
Output:
Hello, and welcome to my world
2. casefold()
casefold()
method returns a string where
all the characters are lower case.casefold()
method is
stronger, more aggressive, meaning that it will convert more characters into
lower case, and will find more matches when comparing two strings and both are
converted using the casefold()
method.txt = "Hello, And Welcome To My World!"
x = txt.casefold()
print(x)
Output: hello, and welcome to my world!
3. str.center()
center()
method will center align the
string, using a specified character (space is default) as the fill character.length | The length of the returned string |
character | The character to fill the missing space on each side. Default is " " (space) |
txt = "banana" x = txt.center(20) print(x)
Output:
banana
4. str.count()
count()
method returns the number of
times a specified value appears in the string.value | A String. The string to value to search for |
start | An Integer. The position to start the search. Default is 0 |
end | An Integer. The position to end the search. Default is the end of the string |
txt = "I love apples, apple is my favorite fruit" x = txt.count("apple") print(x)
Output:
2
5. str.encode()
encode()
method encodes the string,
using the specified encoding. If no encoding is specified, UTF-8 will be used.txt = "My name is Ståle" x = txt.encode() print(x)
Output:
b'My name is St\xc3\xe5le'
6. str.endswith()
endswith()
method returns True if the
string ends with the specified value, otherwise False.value | The value to check if the string ends with |
start | An Integer specifying at which position to start the search |
end | An Integer specifying at which position to end the search |
txt = "Hello, welcome to my world." x = txt.endswith(".") print(x)
Output:
True
7. str.expandtabs()
expandtabs()
method sets the tab size
to the specified number of whitespaces.tabsize | Optional. A number specifying the tabsize. Default tabsize is 8 |
txt = "H\te\tl\tl\to" x = txt.expandtabs(2) print(x)
Output:
H e l l o
8. str.find()
find()
method finds the first
occurrence of the specified value. The find()
method returns -1 if the value
is not found.
The find()
method is almost the same as the index() method, the only difference is that the index()
method raises an exception if the value is not found. (See example below)
Syntax: -> string.find(value, start, end)
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
txt = "Hello, welcome to my world." x = txt.find("welcome") print(x)
Output:
7
9. str.format()
format()
method formats the specified
value(s) and insert them inside the string's placeholder.The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.
The format()
method returns the formatted
string.
Syntax: -> string.format(value1, value2...)
value1, value2... | Required. One or more values that should be formatted and inserted in
the string. The values are either a list of values separated by commas, a key=value list, or a combination of both. The values can be of any data type. |
txt = "For only {price:.2f} dollars!" print(txt.format(price = 49))
Output:
For only 49.00 dollars!
10. str.index()
index()
method finds the first
occurrence of the specified value.index()
method raises an exception if the value is not found.index()
method is almost the same as the find() method, the only difference is that the find()
method returns -1 if the value is not found. (See example below)value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
txt = "Hello, welcome to my world." x = txt.index("welcome") print(x)
Output:
7
11. str.isalnum()
isalnum()
method returns True if all the
characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).Example of characters that are not alphanumeric: (space)!#%&? etc.
Syntax: -> string.isalnum()
Coding;
txt = "Company12" x = txt.isalnum() print(x)
Output:
True
12. str.isalpha()
isalpha()
method returns True if all the
characters are alphabet letters (a-z).Example of characters that are not alphabet letters: (space)!#%&? etc.
Syntax: -> string.isalpha()
Coding;
txt = "CompanyX" x = txt.isalpha() print(x)
Output:
True
13. str.isascii()
isascii()
method returns True if all the
characters are ascii characters (a-z).txt = "Company123★" x = txt.isascii() print(x)
Output:
False
14. str.isdecimal()
isdecimal()
method returns True if all the
characters are decimals (0-9).This method can also be used on unicode objects. See example below.
Syntax: -> string.isdecimal()
Coding;
txt = "1234x" x = txt.isdecimal() print(x)
Output:
False
15. str.isdigit()
isdigit()
method returns True if all the
characters are digits, otherwise False.Exponents, like ², are also considered to be a digit.
Syntax: -> string.isdigit()
Coding;
txt = "50800" x = txt.isdigit() print(x)
Output:
True
16. str.isidentifier()
isidentifier()
method returns True if the
string is a valid identifier, otherwise False.A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.
Syntax: -> string.isidentifier()
Coding;
txt = "Demo" x = txt.isidentifier() print(x)
Output:
True
17. str.islower()
islower()
method returns True if all the
characters are in lower case, otherwise False.Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax: -> string.islower()
Coding;
txt = "hello wOrld!" x = txt.islower() print(x)
Output:
False
18. str.isnumeric()
isnumeric()
method returns True if all the
characters are numeric (0-9), otherwise False.Exponents, like ² and ¾ are also considered to be numeric values.
"-1"
and "1.5"
are NOT considered numeric values,
because all the characters in the string must be numeric, and the -
and the .
are not.
Syntax: -> string.isnumeric()
Coding;
txt = "565543" x = txt.isnumeric() print(x)
Output:
True
19. str.isprintable()
isprintable()
method returns True if all the
characters are printable, otherwise False.Example of none printable character can be carriage return and line feed.
Syntax: -> string.isprintable()
Coding;
txt = "Hello! Are you #1?" x = txt.isprintable() print(x)
Output:
True
20. str.isspace()
isspace()
method returns True if all the
characters in a string are whitespaces, otherwise False.txt = " " x = txt.isspace() print(x)
Output:
True
21. str.istitle()
istitle()
method returns True if all
words in a text start with a upper case letter, AND the rest of the word are
lower case letters, otherwise False.Symbols and numbers are ignored.
Syntax: -> string.istitle()
Coding;
txt = "Hello, And Welcome To My World!" x = txt.istitle() print(x)
Output: True
22. str.isupper()
isupper()
method returns True if all the
characters are in upper case, otherwise False.Numbers, symbols and spaces are not checked, only alphabet characters.
Syntax: -> string.isupper()
Coding;
txt = "THIS IS NoW!" x = txt.isupper() print(x)
Output:
False
23. str.join()
join()
method takes all items in an iterable
and joins them into one string.A string must be specified as the separator.
Syntax: -> string.join(iterable)
*iterable=Any iterable object where all the returned values are strings
Coding;
myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x)
Output: John#Peter#Vicky
24. str.ljust()
ljust()
method will left align the
string, using a specified character (space is default) as the fill character.length | Required. The length of the returned string |
character | Optional. A character to fill the missing space (to the right of the string). Default is " " (space). |
txt = "banana" x = txt.ljust(20) print(x, "is my favorite fruit.")
Output:
banana is my favorite fruit.
25. str.lower()
lower()
method returns a string where
all characters are lower case.Symbols and Numbers are ignored.
Syntax: -> string.lower()
Coding;
txt = "Hello my FRIENDS" x = txt.lower() print(x)
Output:
hello my friends
26. str.lstrip()
lstrip()
method removes any leading
characters (space is the default leading character to remove)txt = " banana "
x = txt.lstrip()
print("of all fruits", x, "is my favorite")
Output:
of all fruits banana is my favorite
27. str.maketrans()
maketrans()
method returns a mapping
table that can be used with the translate() method to replace
specified characters.x | Required. If only one parameter is specified, this has to be a dictionary describing how to perform the replace. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace. |
y | Optional. A string with the same length as parameter x. Each character in the first parameter will be replaced with the corresponding character in this string. |
z | Optional. A string describing which characters to remove from the original string. |
txt = "Hello Sam!" mytable = str.maketrans("S", "P") print(txt.translate(mytable))
Output:
Hello Pam!
28. str.partition()
partition()
method searches for a
specified string, and splits the string into a tuple containing three elements.The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
Syntax: -> string.partition(value to search for)
Coding;
txt = "I could eat bananas all day" x = txt.partition("bananas") print(x)
Output:
('I could eat ', 'bananas', ' all day')
29. str.replace()
replace()
method replaces a specified
phrase with another specified phrase.oldvalue | Required. The string to search for |
newvalue | Required. The string to replace the old value with |
count | Optional. A number specifying how many occurrences of the old value you want to replace. Default is all occurrences |
txt = "I like bananas" x = txt.replace("bananas", "apples") print(x)
Output: I like apples
30. str.rfind()
rfind()
method finds the last
occurrence of the specified value. The rfind()
method returns -1 if the value is not found.
The rfind()
method is almost the same as the rindex() method. See example below.
Syntax: > string.rfind(value, start, end)
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
txt = "Mi casa, su casa." x = txt.rfind("casa") print(x)
Output:
12
31. str.rindex()
rindex()
method finds the last
occurrence of the specified value. The rindex()
method raises an exception if the value is not found.
The rindex()
method is almost the same as the rfind() method. See example below.
Syntax: > string.rindex(value, start, end)
value | Required. The value to search for |
start | Optional. Where to start the search. Default is 0 |
end | Optional. Where to end the search. Default is to the end of the string |
txt = "Mi casa, su casa." x = txt.rindex("casa") print(x)
Output:
12
32. str.rjust()
rjust()
method will right align the
string, using a specified character (space is default) as the fill character.length | Required. The length of the returned string |
character | Optional. A character to fill the missing space (to the left of the string). Default is " " (space). |
txt = "apple" x = txt.rjust(20) print(x, "is my favorite fruit.")
Output:
apple is my favorite fruit.
33. str.rpartition()
rpartition()
method searches for the
last occurrence of a
specified string, and splits the string into a tuple containing three elements.The first element contains the part before the specified string.
The second element contains the specified string.
Syntax: > string.rpartition(value)
Coding;
txt = "I could eat apples all day, bananas are my favorite fruit" x = txt.rpartition("apples") print(x)
Output:
('I could eat apples all day, ', 'bananas', ' are my favorite fruit')
34. str.rsplit()
rsplit()
method splits a string into a
list, starting from the right.If no "max" is specified, this method will return the same as the split() method.
Syntax: > string.rsplit(separator, maxsplit)
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences" |
txt = "apple, banana, cherry" x = txt.rsplit(", ") print(x)
Output:
['apple', 'banana', 'cherry']
35. str.rstrip()
rstrip()
method removes any trailing
characters (characters at the end a string), space is the default trailing
character to remove.txt = " apple " x = txt.rstrip() print("of all fruits", x, "is my favorite")
Output:
of all fruits apple is my favorite
36. str.split()
split()
method splits a string into a
list.You can specify the separator, default separator is any whitespace.
Syntax: > string.split(separator, maxsplit)
separator | Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator |
maxsplit | Optional. Specifies how many splits to do. Default value is -1, which is "all occurrences" |
txt = "welcome to the jungle" x = txt.split() print(x)
Output:
['welcome', 'to', 'the', 'jungle']
37. str.splitlines()
splitlines()
method splits a string into a
list. The splitting is done at line breaks.keeplinebreaks | Optional. Specifies if the line breaks should be included (True), or not
(False). Default value is False |
txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines() print(x)
Output:
['Thank you for the music', 'Welcome to the jungle']
38. str.startswith()
startswith()
method returns True if the
string starts with the specified value, otherwise False.value | Required. The value to check if the string starts with |
start | Optional. An Integer specifying at which position to start the search |
end | Optional. An Integer specifying at which position to end the search |
txt = "Hello, welcome to my world." x = txt.startswith("Hello") print(x)
Output: True
39. str.strip()
strip()
method removes any leading, and trailing whitespaces.Leading means at the beginning of the string, trailing means at the end.
You can specify which character(s) to remove, if not, any whitespaces will be removed.
Syntax: > string.strip(characters)
characters | Optional. A set of characters to remove as leading/trailing characters |
txt = " banana " x = txt.strip() print("of all fruits", x, "is my favorite")
Output:
of all fruits banana is my favorite
40. str.swapcase()
swapcase()
method returns a string where
all the upper case letters are lower case and vice versa.txt = "Hello My Name Is PETER" x = txt.swapcase() print(x)
Output: hELLO mY nAME iS peter
41. str.title()
title()
method returns a string where
the first character in every word is upper case. Like a header, or a title.If the word contains a number or a symbol, the first letter after that will be converted to upper case.
Syntax: > string.title()
Coding;
txt = "Welcome to my world" x = txt.title() print(x)
Output:
Welcome To My World
42. str.translate()
translate()
method returns a string
where some specified characters are replaced with the character described in a dictionary,
or in a mapping table.Use the maketrans() method to create a mapping table.
If a character is not specified in the dictionary/table, the character will not be replaced.
If you use a dictionary, you must use ascii codes instead of characters.
Syntax: > string.translate(table)
table | Required. Either a dictionary, or a mapping table describing how to perform the replace |
#use a dictionary with ascii codes to replace 83 (S) with 80 (P):
mydict = {83: 80}
txt = "Hello Sam!"
print(txt.translate(mydict))
Output: Hello Pam!
43. str.upper()
upper()
method returns a string where
all characters are in upper case.Symbols and Numbers are ignored.
Syntax: > string.upper()
Coding;
txt = "Hello my friends" x = txt.upper() print(x)
Output:
HELLO MY FRIENDS
44. str.zfill()
zfill()
method adds zeros (0) at the
beginning of the string, until it reaches the specified length.If the value of the len parameter is less than the length of the string, no filling is done.
Syntax: > string.zfill(len)
len | Required. A number specifying the desired length of the string |
txt = "50" x = txt.zfill(10) print(x)
Output:
0000000050
Thank you Bro
ReplyDelete