In, this article we will learn how to manipulate strings and also discuss some functions to handle strings.
Accessing String using the concept of Array
As we know that string can be placed inside single or double-quotes. We have also read some string handling in past articles. Now, we will learn how to access string using the concept of arrays. In simple terms, a string is an array of characters. In Python, we can access the individual character of a string using the index method. Let’s understand it with an example.
The first character of the string can be accessed using index 0, the second character using index 1. It means that a string of n characters can be accessed using index 0 to n-1 from first to the last character.
One more interesting thing you will discover that string can also be accessed in a reverse manner, using a negative index. It means that a string of n characters can be accessed in a reverse manner using index -1 to -n from last to the first character.
Enough Talking, Let’s understand this concept using Python Program
Code:
a_string = "Python"
a_length = len(a_string)
print("Length of the String is {}".format(a_length))
print("Let's Print the character of String using index 0 to index n-1")
index = 0
for index in range(0, a_length):
print(a_string[index], end=" ")
print("\nLet's Print the character of String in reverse using index -1 to index -n")
for index in range(1, a_length+1):
print(a_string[-index], end=" ")
print("\n")
print(a_string[0:a_length])
print(a_string[-a_length:-1])
Output:
Length of the String is 6 Let's Print the character of String using index 0 to index n-1 P y t h o n Let's Print the character of String in reverse using index -1 to index -n n o h t y P Python Pytho
Now let’s Study some String functions
capitalize() method
Converts the first character to upper case
Code:
a_string = "python"
print("String after Capitalization is {}".format(a_string.capitalize()))
Output:
String after Capitalization is Python
casefold() method
Converts string into lower case
Code:
a_string = "PYTHON"
print("String after Capitalization is {}".format(a_string.casefold()))
Output:
String after Capitalization is python
center() method
Will center align the string, using a specified character (space is default) as the fill character.
Syntax:
string.center(length, character)
| Parameter | Description |
|---|---|
| length | Required. The length of the returned string |
| character | Optional. The character to fill the missing space on each side. Default is ” ” (space) |
Code:
a_string = "PYTHON"
print("Using the character S as padding character")
print(a_string.center(10, 'S'))
Output:
Using the character S as padding character SSPYTHONSS
count() method
Returns the number of times a specified value occurs in a string
Syntax:
string.count(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. A String. The string to value to search for |
| start | Optional. An Integer. The position to start the search. Default is 0 |
| end | Optional. An Integer. The position to end the search. Default is the end of the string |
Code:
a_string = "Python is no better than Python so I use Python Python"
length = len(a_string)
print(a_string.count("python", 0, length))
print(a_string.count("Python", 0, length))
Output:
0 4
encode() method
method encodes the string, using the specified encoding.
If no encoding is specified, UTF-8 will be used.
Syntax:
string.encode(encoding=encoding, errors=errors)
| Parameter | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| encoding | Optional. A String specifying the encoding to use. Default is UTF-8 | ||||||||||||
| errors | Optional. A String specifying the error method. Legal values are:
|
Code:
a = "I would like to study in Luleå tekniska universitet"
print(a.encode(encoding="utf-8",errors="backslashreplace"))
print(a.encode(encoding="utf-8",errors="ignore"))
print(a.encode(encoding="utf-8",errors="namereplace"))
print(a.encode(encoding="utf-8",errors="replace"))
print(a.encode(encoding="utf-8",errors="xmlcharrefreplace"))
print(a.encode(encoding="utf-8",errors="strict"))
print("The special character 'å' which is not supported in ASCII ")
print(" Can be encoded using UTF-8")
print(a)
Output:
b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' b'I would like to study in Lule\xc3\xa5 tekniska universitet' The special character 'å' which is not supported in ASCII Can be encoded using UTF-8 I would like to study in Luleå tekniska universitet
endswith() method
returns True if the string ends with the specified value, otherwise False.
Syntax:
string.endswith(value, start, end)
| Parameter | Description |
|---|---|
| value | Required. The value to check if the string ends 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 |
Code:
a_string = "Welcome to the World of Python Programming"
True_or_False = a_string.endswith("Programming", 0, len(a_string))
print(True_or_False)
Output:
True
expandtabs() method
sets the tab size to the specified number of whitespaces.
Syntax:
string.exandtabs(tabsize)
| Parameter | Description |
|---|---|
| tabsize | Optional. A number specifying the tabsize. Default tabsize is 8 |
Code:
programming = "P\tr\to\tg\tr\ta\tm\tm\ti\tn\tg" print(programming) print(programming.expandtabs()) print(programming.expandtabs(2)) print(programming.expandtabs(4)) print(programming.expandtabs(10))
Output:
P r o g r a m m i n g P r o g r a m m i n g P r o g r a m m i n g P r o g r a m m i n g P r o g r a m m i n g
find() method
- finds the first occurrence of the specified value.
- find() method returns -1 if the value is not found.
- 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.
Syntax:
string.find(value, start, end)
| Parameter | Description |
|---|---|
| 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 |
Code:
programming = "Welcome to world of Python Programming"
value = programming.find("to", 0, len(programming))
print(value)
print(programming.find("q"))
print(programming.index("q"))
Output:
8
-1
Traceback (most recent call last):
File "practise.py", line 6, in <module>
print(programming.index("q"))
ValueError: substring not found
format() method
We have already discussed the format() method in previous articles String Formatting using {} Curly Brackets and format(). you can visit the link if you want to revise the concept.
index() method
- The index() method finds the first occurrence of the specified value.
- The index() method raises an exception if the value is not found.
- The 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)
Syntax:
string.index(value, start, end)
| Parameter | Description |
|---|---|
| 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 |
Code:
programming = "Welcome to world of Python Programming"
value = programming.index("to", 0, len(programming))
print(value)
print(programming.find("q"))
print(programming.index("q"))
Output:
8
-1
Traceback (most recent call last):
File "practise.py", line 6, in <module>
print(programming.index("q"))
ValueError: substring not found
isalnum() Method
- returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9).
Syntax:
string.isalnum()
Code:
programming = "Welcome to world of Python Programming 3" programming_1 = "WelcometoworldofPythonProgramming3" x = programming.isalnum() print(x) x = programming_1.isalnum() print(x)
Output:
False True
isdecimal() Method
- isdecimal() method returns True if all the characters are decimals (0-9). This method is used on unicode objects.
Syntax:
string.isdecimal()
Code:
a = "\u0030" #unicode for 0 b = "\u0047" #unicode for G c = "11" print(a.isdecimal()) print(b.isdecimal()) print(c.isdecimal())
Output:
True False True
isdigit() Method
- isdigit() method returns True if all the characters are digits, otherwise False. Exponents, like ², are also considered to be a digit.
Syntax:
string.isdigit()
Code:
a = "\u0030" #unicode for 0 b = "\u00B2" #unicode for ² c = "32" print(a.isdigit()) print(b.isdigit()) print(c.isdigit())
Output:
True True True
isidentifier() Method
- 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()
Code:
a = "_Python" b = "3Python" c = "Python" d = "Python 3" e = "Python_3" print(a.isidentifier()) print(b.isidentifier()) print(c.isidentifier()) print(d.isidentifier()) print(e.isidentifier())
Output:
True False True False True
islower() Method
- 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.
Syntax:
string.islower()
Code:
a = "_python" b = "3Python" c = "python" d = "Python 3" e = "python_3" print(a.islower()) print(b.islower()) print(c.islower()) print(d.islower()) print(e.islower())
Output:
True False True False True
isnumeric() Method
- 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.
Syntax:
string.isnumeric()
Code:
a = "_python" b = "35909" c = "45 789" d = "1033" e = "python_33" print(a.isnumeric()) print(b.isnumeric()) print(c.isnumeric()) print(d.isnumeric()) print(e.isnumeric())
Output:
False True False True False
isprintable() Method
- 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.
Syntax:
string.isprintable()
Code:
programmer = "Hello!\n I am a #Python Programmer" x = programmer.isprintable() print(x)
Output:
False
isspace() Method
- The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Syntax:
string.isspace()
Code:
programmer = "I am a #Python Programmer" code = " " x = programmer.isspace() print(x) y = code.isspace() print(y)
Output:
False True
istitle() Method
- The 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()
Code:
a = "WELCOME TO PYTHON PROGRAMMING" b = "Welcome, To World Of Python" c = "22 Python is good" d = "This Is Python" print(a.istitle()) print(b.istitle()) print(c.istitle()) print(d.istitle())
Output:
False True False True
isupper() Method
- 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.
Syntax:
string.isupper()
Code:
a = "3 PYTHON 123 PROGRAMMING" b = "Welcome, To World Of Python" c = "22 is good" d = "@THIS IS PYTHON" print(a.isupper()) print(b.isupper()) print(c.isupper()) print(d.isupper())
Output:
True False False True
join() Method
- The 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)
| Parameter | Description |
|---|---|
| iterable | Required. Any iterable object where all the returned values are strings |
Code:
demo_list = ["Program_number_", "Python_Version_", "Test_case_"] test_string = "3" result_list = test_string.join(demo_list) print(result_list, "\n")
Output:
Program_number_3Python_Version_3Test_case_
ljust() Method
- The ljust() method will left align the string, using a specified character (space is default) as the fill character.
Syntax:
string.ljust(length, character)
| Parameter | Description |
|---|---|
| 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). |
Code:
programming = "Python" x = programming.ljust(20, "3") print(x)
Output:
Python33333333333333
lower() Method
- The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.
Syntax:
string.lower()
Code:
string_1 = "Python 3 Programs" string_2 = "PYTHON_3_PROGRAMMING" x = string_1.lower() y = string_2.lower() print(x) print(y)
Output:
python 3 programs python_3_programming
lstrip() Method
- The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax:
string.lstrip(characters)
Code:
string_1 = "P ython Programs"
string_2 = " p h t h o n p r o g r a m s"
x = string_1.lstrip("P ")
y = string_2.lstrip("p h")
print(x)
print(y)
Output:
ython Programs t h o n p r o g r a m s
lstrip() Method
- The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax:
string.lstrip(characters)
Code:
string_1 = "P ython Programs"
string_2 = " p h t h o n p r o g r a m s"
x = string_1.lstrip("P ")
y = string_2.lstrip("p h")
print(x)
print(y)
Output:
ython Programs t h o n p r o g r a m s
partition() Method
- 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)
| Parameter | Description |
|---|---|
| value | Required. The string to search for |
Code:
string_1 = "I could eat bananas all day"
x = string_1.partition("bananas")
print(x)
Output:
('I could eat ', 'bananas', ' all day')
replace() Method
- 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)
Code:
string_1 = "C++ Programming is good C++ is best"
x = string_1.replace("C++", "Python")
print(x)
string_2 = "C++ Programming is C++ good C++ is best"
x = string_2.replace("C++", "Python", 2)
print(x)
Output:
Python Programming is good Python is best Python Programming is Python good C++ is best
rfind() Method
- 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)
Code:
string_1 = "Python Programming, Is Python Programming"
x = string_1.rfind("Python")
print(x)
Output:
23
rjust() Method
- 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)
| Parameter | Description |
|---|---|
| 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). |
Code:
programming = "Python" x = programming.rjust(20, "3") print(x)
Output:
33333333333333Python
rpartition() Method
- 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)
| Parameter | Description |
|---|---|
| value | Required. The string to search for |
Code:
string_1 = "Python Programming is Python Programming"
x = string_1.rpartition("Python")
print(x)
Output:
('Python Programming is ', 'Python', ' Programming')
rsplit() Method
- 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)
| Parameter | Description |
|---|---|
| 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” |
Code:
string_1 = "Long, Live, Python, Programming"
x = string_1.rsplit(",")
print(x)
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = string_1.rsplit(",",1)
print(x)
# setting the maxsplit parameter to 2, will return a list with 3 elements!
x = string_1.rsplit(",",2)
print(x)
# setting the maxsplit parameter to 3, will return a list with 4 elements!
x = string_1.rsplit(",",3)
print(x)
Output:
['Long', ' Live', ' Python', ' Programming'] ['Long, Live, Python', ' Programming'] ['Long, Live', ' Python', ' Programming'] ['Long', ' Live', ' Python', ' Programming']
rstrip() Method
- 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)
| Parameter | Description |
|---|---|
| characters | Optional. A set of characters to remove as trailing characters |
Code:
string_1 = "Python Programm ing"
x = string_1.rstrip("ing")
print(x)
Output:
Python Programm
split() Method
- 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)
| Parameter | Description |
|---|---|
| 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” |
Code:
#Split the string, using comma, followed by a space, as a separator:
string_1 = "I, love, Python, Programming"
x = string_1.split(", ")
print(x)
string_2 = "I#love#Python#Programming"
# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = string_2.split("#", 1)
print(x)
Output:
['I', 'love', 'Python', 'Programming'] ['I', 'love#Python#Programming']
splitlines() Method
- The splitlines() method splits a string into a list. The splitting is done at line breaks.
Syntax:
string.splitlines(keeplinebreaks)
| Parameter | Description |
|---|---|
| keeplinebreaks | Optional. Specifies if the line breaks should be included (True), or not (False). Default value is not (False) |
Code:
string_1 = "I\nLove\nPython Programming" x = string_1.splitlines(True) print(x) y = string_1.splitlines(False) print(y)
Output:
['I\n', 'Love\n', 'Python Programming'] ['I', 'Love', 'Python Programming']
startswith() Method
- The startswith() method returns True if the string starts with the specified value, otherwise False.
Syntax:
string.startswith(value, start, end)
| Parameter | Description |
|---|---|
| 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 |
Code:
#Check if position 2 to End of string, starts with the characters "thon"
string_1 = "Python Programming"
x = string_1.startswith("thon", 2, len(string_1))
print(x)
Output:
False
strip() Method
- 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)
| Parameter | Description |
|---|---|
| characters | Optional. A set of characters to remove as leading/trailing characters |
Code:
string_1 = ",,,,,Python Programming@@@@@"
x = string_1.strip(",@")
print(x)
Output:
Python Programming
swapcase() Method
- The swapcase() method returns a string where all the upper case letters are lower case and vice versa.
Syntax:
string.swapcase()
Code:
string_1 = "Python Programming" string_2 = "I LOVE PYTHON" string_3 = "python is cool" x = string_1.swapcase() print(x) x = string_2.swapcase() print(x) x = string_3.swapcase() print(x)
Output:
pYTHON pROGRAMMING i love python PYTHON IS COOL
title() Method
- 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.
Syntax:
string.title()
Code:
string_1 = "python programming" string_2 = "i love pYthon" string_3 = "Python is cOOL" x = string_1.title() print(x) x = string_2.title() print(x) x = string_3.title() print(x)
Output:
Python Programming I Love Python Python Is Cool
upper() Method
- The upper() method returns a string where all characters are in upper case.Symbols and Numbers are ignored.
Syntax:
string.upper()
Code:
string_1 = "python programming" string_2 = "i love pYthon" string_3 = "Python is cOOL" x = string_1.upper() print(x) x = string_2.upper() print(x) x = string_3.upper() print(x)
Output:
PYTHON PROGRAMMING I LOVE PYTHON PYTHON IS COOL
zfill() Method
- 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)
| Parameter | Description |
|---|---|
| len | Required. A number specifying the position of the element you want to remove |
Code:
a = "Python" b = "Welcome to the world of Python Programming" c = "109.87" print(a.zfill(10)) print(b.zfill(10)) print(c.zfill(10))
Output:
0000Python Welcome to the world of Python Programming 0000109.87