String Operations in Python
String Operations in Python
String
Python string is the collection of the characters surrounded by single quotes, double quotes, or triple quotes. The
computer does not understand the characters; internally, it stores manipulated character as the combination of the 0's
and 1's.
Each character is encoded in the ASCII or Unicode character. So we can say that Python strings are also called the
collection of Unicode characters.
In Python, strings can be created by enclosing the character or the sequence of characters in the quotes. Python allows
us to use single quotes, double quotes, or triple quotes to create the string.
Example:
str="Nielit"
print(type(str)) Output: <class 'str'>
In Python, strings are treated as the sequence of characters, which means that Python doesn't support the character
data-type;
type; instead, a single character written as 'N' is treated as the string of length 1.
Indexing in String
Like other languages, the indexing of the Python strings starts from 0. For example, the string "HELLO" is indexed as
given in the below figure.
Page 1 of 6
Slice operator [] in String
As shown in Python, the slice operator [] is used to access the individual characters of the string. However, we can use
the: (colon) operator in Python to access the substring from the given string.
Example.
Reassigning Strings
Updating the content of the strings is as easy as assigning it to a new string. The string object doesn't support item
assignment i.e., A string can only be replaced with new string since its content cannot be partially replaced. Strings are
immutable in Python.
Example
str = "PYTHON"
str[0] = "p"
print(str) Output: str[0] = "p“
TypeError: 'str' object does not support item assignment
Ex.1: Return the number of times the value "apple" appears in the string:
txt = "I love apples, apple are my favorite fruit"
x = txt.count("apple")
print(x) Output: 2
Page 2 of 6
find()
The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
Syntax: string.find(value, start, end)
Ex.2: Where in the text is the first occurrence of the letter "e" when you only search between position 5 and
10?:
txt = "Hello,welcome to my world."
x = txt.find("e", 5, 10)
print(x) Output: 8
rfind(): The rfind() searches the string for a specified value and returns the last position of where it was found.
The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
Syntax: string.rfind(value, start, end)
Ex.1: Where in the text is the last occurrence of the string "nielit"?:
txt = "nielit gorakhpur has started o level course. nielit gorakhpur"
x = txt.rfind("nielit")
print(x) Output: 43
Ex.2: Where in the text is the last occurrence of the letter "e" when you only search between position 5 & 10?:
txt = "Hello, welcome to NIELIT Gorakhpur."
x = txt.rfind("e", 5, 10)
print(x) Output: 8
capitalize():
This method converts the first character to upper case. The capitalize() method returns a string where the first
character is upper case.
Ex.1: Upper case the first letter in this sentence:
txt = "hello, welcome to NIELIT Gorakhpur."
x = txt.capitalize()
print (x) Output: Hello, welcome to nielit gorakhpur.
title()
The title() method returns a string where the first character in every word is upper case. Like a header, or a title.
Ex.1:
txt = "python programming using string"
x = txt.title()
print(x) Output: Python Programming Using String
If the word contains a number or a symbol, the first letter after that will be converted to upper case.
Ex.2:
txt = " 3rd generation python"
x = txt.title()
print(x) Output: 3Rd Generation Python
Page 3 of 6
Ex.3: Note that the first letter after a non-alphabet letter is converted into a upper case letter:
txt = "hello b2b2b2 and 3g3g3g"
x = txt.title()
print(x) Output: Hello B2B2B2 And 3G3G3G
lower()
The lower() method returns a string where all characters are lower case. Symbols and Numbers are ignored.
Ex.1:
txt = "Welcome To NIELIT Gorakhpur "
x = txt.lower()
print(x) Output: welcome to nielit gorakhpur
upper()
The upper() method returns a string where all characters are in upper case. Symbols and Numbers are ignored.
Ex.1:
txt = "Welcome To NIELIT Gorakhpur "
x = txt.upper()
print(x) Output: WELCOME TO NIELIT GORAKHPUR
replace()
The replace() method replaces a specified phrase with another specified phrase.
Syntax: string.replace(oldvalue, newvalue, count)
Parameter Values
Parameter Description
oldvalue Required. The string to search for
newvalue Required. The string to replace the old value with
Optional. A number specifying how many occurrences of the old value you want to replace.
count
Default is all occurrences
split():
The split() method splits a string into a list. You can specify the separator, default separator is any whitespace.
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"
Page 4 of 6
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.
Syntax string.partition(value)
Where, value is required. The value is the string to search for
Example
txt = "I could eat bananas all day"
x = txt.partition("bananas")
print(x) Output: ('I could eat ', 'bananas', ' all day')
Search for the word "bananas", and return a tuple with three elements:
1 - everything before the "banana"
2 - the "banana"
3 - everything after the "banana"
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)
Ex.1: Remove spaces at the beginning and at the end of the string:
txt = " banana "
x = txt.strip()
print(x) Output: banana
lstrip()
The lstrip() method removes any leading characters (space is the default leading character to remove)
Syntax : string.lstrip(characters)
Where, character is Optional. A set of characters to remove as leading characters
Ex.1:
txt = ",,,,,ssaaww.....banana.. "
x = txt.lstrip(",.asw")
print(x) Output: banana..
Note: Only leading character on left side will be removed.
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)
Where, characters is optional. A set of characters to remove as trailing characters
Ex.1:
txt = "banana,,,,,ssaaww....."
x = txt.rstrip(",.asw")
print(x) Output: banana..
Note: Only leading character on right side will be removed.
Page 5 of 6
String Logical Functions
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) Output: True
isupper()
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 = "PYTHON PROGRAM"
x = txt.isupper()
print(x) Output: True
istitle()
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.
Example:
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())
Output: False
True
True
True
isspace()
The isspace() method returns True if all the characters in a string are whitespaces, otherwise False.
Example: txt = " s "
x = txt.isspace()
print(x) Output: False
Page 6 of 6