Hey! Everyone I hope y’all are doing great in your life. so today we will be further continuing to discuss more built-in Python String Functions.
If you haven’t read the first part do check it out first over here: Python String Functions
Index()
The index()
function/method finds the first occurrence of the specified value. It raises an exception if the value is not found. It’s almost the same as the find()
method, the only difference is that the find()
method returns -1 if the value is not found.
Syntax:
string.index(value, start, end)
Value is the value to search for.
Start is used to tell where to start the search from. The default is zero.
End is used to tell where to end the search. The default is the end of the string.
Example:
Where in the text is the first occurrence of the letter “e”?
txt = "Hello, welcome to my world." x = txt.index("e") print(x) Result: 1
OR
Where in the text is the first occurrence of the letter “e” when you only search between positions 5 and 10?
txt = "Hello, welcome to my world." x = txt.index("e", 5, 10) print(x) Result: 8
OR
If the value is not found, the find() method returns -1, but the index() method will raise an exception.
txt = "Hello, welcome to my world." print(txt.find("q")) print(txt.index("q")) Result: -1 Traceback (most recent call last): File "./prog.py", line 4, in <module> ValueError: substring not found
isalnum()
The isalnum()
method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
characters that are not alphanumeric: (space)!#%&? etc.
Example:
txt = "Company 12" x = txt.isalnum() print(x) Result: False
OR
txt = "Company12" x = txt.isalnum() print(x) Result: True
isalpha()
The isalpha()
method returns True if all the characters are alphabet letters (a-z).
Example:
txt = "CompanyX" x = txt.isalpha() print(x) Result: True
OR
txt = "Company7" x = txt.isalpha() print(x) Result: False
Also Read: Web Scrapping with Python
isdecimal()
The isdecimal()
method returns True if all the characters are decimals (0-9). This method is used on Unicode objects.
txt = "\u0033" #unicode for 3 x = txt.isdecimal() print(x) Result: True
OR
a = "\u0030" #unicode for 0 b = "\u0047" #unicode for G print(a.isdecimal()) print(b.isdecimal()) Result: True False
isdigit()
The isdigit()
method returns True if all the characters are digits, otherwise False. Exponents, like ², are also considered to be a digit.
Example:
txt = "50800" x = txt.isdigit() print(x) Result: True
OR
a = "\u0030" #unicode for 0 b = "\u00B2" #unicode for ² print(a.isdigit()) print(b.isdigit()) Result: True True
isidentifier()
The 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.
Example:
txt = "Demo" x = txt.isidentifier() print(x) Result: True
OR
a = "MyFolder" b = "Demo002" c = "2bring" d = "my demo" print(a.isidentifier()) print(b.isidentifier()) print(c.isidentifier()) print(d.isidentifier()) Result: True True False False
islower()
The islower()
method returns True if all the characters are in lower case, otherwise False. Numbers, symbols, and spaces are not checked, only alphabet characters.
Example:
txt = "hello world!" x = txt.islower() print(x) Result: True
OR
a = "Hello world!" b = "hello 123" c = "mynameisPeter" print(a.islower()) print(b.islower()) print(c.islower()) Result: False True False
isnumeric()
The isnumeric()
method returns True if all the characters are numeric (0-9), otherwise False.
Exponents, like ² and ¾, are also considered to be numeric values.
Example:
txt = "565543" x = txt.isnumeric() print(x) Result: True
OR
a = "\u0030" #unicode for 0 b = "\u00B2" #unicode for ² c = "10km2" print(a.isnumeric()) print(b.isnumeric()) print(c.isnumeric()) Result: True True False
isprintable()
The isprintable()
method returns True if all the characters are printable, otherwise False.
Examples of none printable characters can be carriage return and line feed.
Example:
txt = "Hello! Are you #1?" x = txt.isprintable() print(x) Result:True
OR
txt = "Hello!\nAre you #1?" x = txt.isprintable() print(x) Result: False
isspace()
The isspace()
method returns True if all the characters in a string are whitespaces, otherwise False.
Example:
txt = " " x = txt.isspace() print(x) Result: True
OR
txt = " s " x = txt.isspace() print(x) Result: False
Also Read: Add Multiple Magnet Links in Transmission Using Python
istitle()
The istitle()
method returns True if all words in a text start with an upper case letter, AND the rest of the word is lower case letters, otherwise False.
Symbols and numbers are ignored.
Example:
txt = "Hello, And Welcome To My World!" x = txt.istitle() print(x) Result: True
OR
a = "HELLO, AND WELCOME TO MY WORLD" b = "Hello" c = "22 Names" d = "This Is %'!?" print(a.istitle()) print(b.istitle()) print(c.istitle()) print(d.istitle()) Result: False True True True
isuper()
The isupper()
method returns True if all the characters are in upper case, otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.
Example:
txt = "THIS IS NOW!" x = txt.isupper() print(x) Result: True
OR
a = "Hello World!" b = "hello 123" c = "MY NAME IS PETER" print(a.isupper()) print(b.isupper()) print(c.isupper()) Result: False False True
join()
The join()
method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.
Note: When using a dictionary as an iterable, the returned values are the keys, not the values.
Syntax:
string.join(iterable)
iterable: Any iterable object where all the returned values are strings
Example:
myTuple = ("John", "Peter", "Vicky") x = "#".join(myTuple) print(x) Result: John#Peter#Vicky
OR
myDict = {"name": "John", "country": "Norway"} mySeparator = "TEST" x = mySeparator.join(myDict) print(x) Result: nameTESTcountry
ljust()
The ljust()
method will left align the string, using a specified character (space is default) as the fill character.
Syntax:
string.ljust(length, character)
Length required for the length of the returned string.
Character to fill the missing space (to the right of the string). Default is ” ” (space).
Example:
txt = "apple" x = txt.ljust(20) print(x, "is my favorite fruit.") Result: apple is my favorite fruit.
OR
Using the letter “O” as the padding character
txt = "banana" x = txt.ljust(20, "O") print(x) Result: bananaOOOOOOOOOOOOOO
lower()
The lower()
method returns a string where all characters are lower case.
Symbols and Numbers are ignored.
Example:
txt = "Hello my FRIENDS" x = txt.lower() print(x) Result:hello my friends
lstrip
The lstrip()
method removes any leading characters (space is the default leading character to remove).
Syntax
string.lstrip(characters)
Characters: A set of characters to remove as leading characters
Example:
txt = " banana " x = txt.lstrip() print("of all fruits", x, "is my favorite") Result: of all fruits banana is my favorite
OR
txt = ",,,,,ssaaww.....banana" x = txt.lstrip(",.asw") print(x) Result: banana
partition()
The 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.
Note: This method search for the first occurrence of the specified string.
Syntax:
string.partition(value)
Value: The string to search for
Example:
Search for the word “bananas”, and return a tuple with three elements:
1 – everything before the “match”
2 – the “match”
3 – everything after the “match”
txt = "I could eat bananas all day" x = txt.partition("bananas") print(x) Result: ('I could eat ', 'bananas', ' all day')
OR
If the specified value is not found, the partition() method returns a tuple containing: 1 – the whole string, 2 – an empty string, 3 – an empty string:
txt = "I could eat bananas all day" x = txt.partition("apples") print(x) Result: ('I could eat bananas all day', '', '')
Also Read: How to Install Django
replace()
The replace()
method replaces a specified phrase with another specified phrase.
Note: All occurrences of the specified phrase will be replaced if nothing else is specified.
Syntax:
string.replace(oldvalue, newvalue, count)
Oldvalue is required for the string to search for.
Newvalue is required for the string to replace the old value.
Count is a number specifying how many occurrences of the old value you want to replace. Default is all occurrences.
Example:
txt = "I like bananas" x = txt.replace("bananas", "apples") print(x) Result: I like apples
OR
txt = "one one was a race horse, two two was one too." x = txt.replace("one", "three") print(x) Result: three three was a race horse, two two was three too."
OR
txt = "one one was a race horse, two two was one too." x = txt.replace("one", "three", 2) print(x) Result: three three was a race horse, two two was one too."
rfind()
The 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.
Syntax:
string.rfind(value, start, end)
Value: The value to search for
Start: Where to start the search. The default is 0.
End: Where to end the search. The default is to the end of the string.
Example:
txt = "Mi casa, su casa." x = txt.rfind("casa") print(x) Result: 12
OR
txt = "Hello, welcome to my world." x = txt.rfind("e") print(x) Result: 13
OR
txt = "Hello, welcome to my world." x = txt.rfind("e", 5, 10) print(x) Result: 8
rindex()
The 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.
Syntax:
string.rindex(value, start, end)
Value: The value to search for
Start: Where to start the search. The default is 0.
End: Where to end the search. The default is to the end of the string.
Example:
txt = "Mi casa, su casa." x = txt.rindex("casa") print(x) Result: 12
OR
txt = "Hello, welcome to my world." x = txt.rindex("e") print(x) Result: 13
OR
txt = "Hello, welcome to my world." x = txt.rindex("e", 5, 10) print(x) Result: 8
OR
If the value is not found, the rfind() method returns -1, but the rindex() method will raise an exception:
txt = "Hello, welcome to my world." print(txt.rfind("q")) print(txt.rindex("q")) Result: -1 Traceback (most recent call last): File "demo_ref_string_rfind_vs_rindex.py", line 4 in <module> print(txt.rindex("q")) ValueError: substring not found
rjust()
The rjust()
method will right-align the string, using a specified character (space is the default) as the fill character.
Syntax:
string.rjust(length, character)
Length required for the length of the returned string.
Character to fill the missing space (to the right of the string). Default is ” ” (space).
Example:
txt = "banana" x = txt.rjust(20) print(x, "is my favorite fruit.") Result: banana is my favorite fruit.
OR
txt = "banana" x = txt.rjust(20, "O") print(x) Result: OOOOOOOOOOOOOObanana
rpartition
The 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.
The third element contains the part after the string.
Syntax:
string.rpartition(value)
Value: The string to search for
Example:
Search for the last occurrence of the word “bananas”, and return a tuple with three elements:
1 – everything before the “match”
2 – the “match”
3 – everything after the “match”
txt = "I could eat bananas all day, bananas are my favorite fruit" x = txt.rpartition("bananas") print(x) Result: ('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')
OR
If the specified value is not found, the rpartition() method returns a tuple containing: 1 – the whole string, 2 – an empty string, 3 – an empty string:
txt = "I could eat bananas all day, bananas are my favorite fruit" x = txt.rpartition("apples") print(x) Result: ('I could eat bananas all day, bananas are my favorite fruit', '', '')
Also Read: Shell Scripting- Variables
rsplit()
The 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.
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax:
string.rsplit(separator, maxsplit)
Separator: It’s optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator.
Maxsplit: It’s optional. Specifies how many splits to do. Default value is -1, which is “all occurrences”.
Example:
txt = "apple, banana, cherry" x = txt.rsplit(", ") print(x) Result: ['apple', 'banana', 'cherry']
OR
txt = "apple, banana, cherry" # setting the maxsplit parameter to 1, will return a list with 2 elements! x = txt.rsplit(", ", 1) print(x) Result: ['apple, banana', 'cherry']
rstrip()
The rstrip()
method removes any trailing characters (characters at the end a string), space is the default trailing character to remove.
Syntax:
string.rstrip(characters)
Character: A set of characters to remove as trailing characters.
txt = " banana " x = txt.rstrip() print("of all fruits", x, "is my favorite") Result: of all fruits banana is my favorite
OR
txt = "banana,,,,,ssqqqww....." x = txt.rstrip(",.qsw") print(x) Result: banana
split()
The split()
method splits a string into a list.
You can specify the separator, default separator is any whitespace.
Note: When maxsplit is specified, the list will contain the specified number of elements plus one.
Syntax:
string.split(separator, maxsplit)
Separator: It’s optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator.
Maxsplit: It’s optional. Specifies how many splits to do. Default value is -1, which is “all occurrences”.
Example:
txt = "welcome to the jungle" x = txt.split() print(x) Result: ['welcome', 'to', 'the', 'jungle']
txt = "hello, my name is Peter, I am 26 years old" x = txt.split(", ") print(x) Result: ['hello', 'my name is Peter', 'I am 26 years old']
OR
txt = "apple#banana#cherry#orange" x = txt.split("#") print(x) Result: ['apple', 'banana', 'cherry', 'orange']
OR
txt = "apple#banana#cherry#orange" # setting the maxsplit parameter to 1, will return a list with 2 elements! x = txt.split("#", 1) print(x) Result: ['apple', 'banana#cherry#orange']
splitlines()
The splitlines()
method splits a string into a list. The splitting is done at line breaks.
Syntax:
string.splitlines(keeplinebreaks)
keeplinebreaks: Specifies if the line breaks should be included (True), or not (False). Default value is not (False).
Example:
txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines() print(x) Result: ['Thank you for the music', 'Welcome to the jungle']
OR
txt = "Thank you for the music\nWelcome to the jungle" x = txt.splitlines(True) print(x) Result: ['Thank you for the music\n', 'Welcome to the jungle']
startswith()
The startswith()
method returns True if the string starts with the specified value, otherwise False.
Syntax:
string.startswith(value, start, end)
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
Example:
txt = "Hello, welcome to my world." x = txt.startswith("Hello") print(x) Result: True
OR
txt = "Hello, welcome to my world." x = txt.startswith("wel", 7, 20) print(x) Result: True
Also Read: Introduction to Wazuh Open Source SIEM
Strip()
The strip()
method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (space is the default leading character to remove)
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") Result: of all fruits banana is my favorite
OR
txt = ",,,,,rrttgg.....banana....rrr" x = txt.strip(",.grt") print(x) Result: banana
swapcase()
The swapcase()
method returns a string where all the upper case letters are lower case and vice versa.
Example:
txt = "Hello My Name Is PETER" x = txt.swapcase() print(x) Result: hELLO mY nAME iS peter
title()
The 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.
Example:
txt = "Welcome to my world" x = txt.title() print(x) Result: Welcome To My World
OR
txt = "hello b2b2b2 and 3g3g3g" x = txt.title() print(x) Result: Hello B2B2B2 And 3G3G3G
OR
txt = "Welcome to my 2nd world" x = txt.title() print(x) Result: Welcome To My 2Nd World
upper()
The upper()
method returns a string where all characters are in upper case.
Symbols and Numbers are ignored.
Syntax:
string.upper()
Example:
txt = "Hello my friends" x = txt.upper() print(x) Result: HELLO MY FRIENDS
zfill()
The 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: A number specifying the position of the element you want to remove.
Example:
txt = "50" x = txt.zfill(10) print(x) Result:0000000050
OR
a = "hello" b = "welcome to the jungle" c = "10.000" print(a.zfill(10)) print(b.zfill(10)) print(c.zfill(10)) Result: 00000hello welcome to the jungle 000010.000
I hope you find this article helpful. If you have any question use the comment section and feel free to leave some suggestions too.