Chapter 9
STRING MANIPULATION
String
Python string is the collection of the characters surrounded by single quotes, double
quotes, or triple quotes
Syntax: str = "Hi Python !"
Strings indexing and splitting
The indexing of the Python strings starts from 0. For example, The string "HELLO" is
indexed as given in the below figure.
Consider the following example:
str = "HELLO"
print(str[0])
print(str[1])
print(str[2])
print(str[3])
print(str[4])
# It returns the IndexError because 6th index doesn't exist
print(str[6])
Output:
H
E
L
L
O
IndexError: string index out of range
NOTE: The slice operator [] is used to access the individual characters of the string.
(colon) operator in Python to access the substring from the given string
Consider the following example.
EXAMPLE:
str = "JAVATPOINT"
# Start Oth index to end
print(str[0:])
# Starts 1th index to 4th index
print(str[1:5])
# Starts 2nd index to 3rd index
print(str[2:4])
# Starts 0th to 2nd index
print(str[:3])
#Starts 4th to 6th index
print(str[4:7])
Output:
JAVATPOINT
AVAT
VA
JAV
TPO
String Operators
Operator Description
It is known as concatenation operator used to
+ join the strings given either side of the
operator.
It is known as repetition operator. It
* concatenates the multiple copies of the same
string.
It is known as slice operator. It is used to
[]
access the sub-strings of a particular string.
It is known as range slice operator. It is used to
[:] access the characters from the specified
range.
It is known as membership operator. It returns
In if a particular sub-string is present in the
specified string.
It is also a membership operator and does the
not in exact reverse of in. It returns true if a particular
substring is not present in the specified string.
It is used to specify the raw string. Raw strings
are used in the cases where we need to print
the actual meaning of escape characters such
r/R
as "C://python". To define any string as a raw
string, the character r or R is followed by the
string.
It is used to perform string formatting. It makes
use of the format specifiers used in C
% programming like %d or %f to map their values
in python. We will discuss how formatting is
done in python.
str = "Hello"
str1 = " world"
print(str*3) # prints HelloHelloHello
print(str+str1) # prints Hello world
print(str[4]) # prints o
print(str[2:4]) # prints ll
print('w' in str) # prints false as w is not present in str
print('wo' not in str1) # prints false as wo is present in str1.
print(r'C://python37') # prints C://python37 as it is written
print("The string str : %s"%(str)) # prints The string str : Hello
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Escape Sequence
The backslash(/) symbol denotes the escape sequence. The backslash can be followed by a special
character and it interpreted differently. The single quotes inside the string must be escaped. We can
apply the same as in the double quotes.
# using triple quotes
print('''''They said, "What's there?"''')
# escaping single quotes
print('They said, "What\'s going on?"')
# escaping double quotes
print("They said, \"What's going on?\"")
Output:
They said, "What's there?"
They said, "What's going on?"
They said, "What's going on?"
Python String functions
Python provides various in-built functions that are used for string handling. Many String
fun
Method Description Example
s = "hello WORLD"
It capitalizes the first character of the String. This function
capitalize() res = s.capitalize()
is deprecated in python3 print(res)
OUTPUT: Hello world
s = "hello world"
count(string,begin, It counts the number of occurrences of a substring in a res = s.count("o")
end) String between begin and end index.
print(res)
OUTPUT: 2
txt = "Hello, welcome to my world."
x = txt.find("welcome")
find(substring ,beginIn It returns the index value of the string where substring is
dex, endIndex) found between begin index and end index.
print(x)
output: 7
s = "Python programming"
index(subsring, position = s.index("prog")
It throws an exception if string is not found. It works same
beginIndex,
as find() method.
endIndex) print(position)
output:7
isalnum() It returns true if the characters in the string are s = "Python123" res = s.isalnum() p
alphanumeric i.e., alphabets or numbers and there is at
least 1 character. Otherwise, it returns false.
output:true
s1 = "HelloWorld" res1 = s1.isalpha
It returns true if all the characters are alphabets and there
isalpha() print(res1)
is at least one character, otherwise False.
output: True
txt = "50800"
x = txt.isdigit()
It returns true if all the characters are digits and there is at
isdigit() print(x)
least one character, otherwise False.
Output:
len(string) It returns the length of a string.
It returns false if characters of a string are in Upper case,
isupper()
otherwise False.
It returns true if the characters of a string are in lower
islower()
case, otherwise false.
lower() It converts all the characters of a string to Lower case.
txt = "I like bananas"
It replaces the old sequence of characters with the new x = txt.replace("bananas", "apples")
replace(old,new
sequence. The max characters are replaced if max is
[,count])
given. print(x)
Output: I like apples
upper() It converts all the characters of a string to Upper Case.
lstrip() It removes all leading whitespaces of a string and can also txt = " banana "
be used to remove particular character from leading. x = txt.lstrip()
print("of all fruits", x, "is my favorite")
Output: of all fruits bana
is my favorite
txt = " banana "
x = txt.rstrip()
It removes all trailing whitespace of a string and can also be
rstrip() print("of all fruits", x, "is my favorite")
used to remove particular character from trailing.
Output:
of all fruits banana is my favorite
txt = "I could eat bananas all day"
x = txt.partition("bananas")
It searches for the separator sep in S, and returns the part
partition() before it, the separator itself, and the part after it. If the print(x)
separator is not found, return S and two empty strings.
('I could eat ', 'bananas', ' a
var = "Geeks for Geeks"
print(var.startswith("Geeks")
startswith(str,beg=0, It returns a Boolean value if the string starts with given str print(var.startswith("Hello")
end=len(str)) between begin and end.
Output: True
False
txt = "welcome to the jungle"
Splits the string according to the delimiter str. The string x = txt.split()
split(str,num=string. splits according to the space if the delimiter is not
count(str)) provided. It returns the list of substring concatenated with print(x)
the delimiter.
Output: ['welcome', 'to', 'th
'jungle']
join() Converts the elements of an iterable into a string a = ['Hello', 'world', 'from', 'Python']
res = ' '.join(a) print(res)
Output:Hello world from Pyth
s = " Hello Python! "
Returns the string with both leading and trailing characters res = s.strip()
strip()
print(res)
Output : Hello Python!
string = "geeksforgeeks"
Returns true if the string ends with the specified print(string.endswith("geeks"))
endswith()
value
Output :True
txt = "I love apples, apple are my favorit
x = txt.count("apple")
print(x)
Count() Returns the number of occurrences of a
substring in the string.
Output :2
Return the number of times the value "apple" appears in the string:
txt = "Hello, welcome to my world."
x = txt.endswith(".")
print(x)
txt = "Hello, welcome to my world."
x = txt.find("welcome")
print(x)
txt = "Hello, welcome to my world."
x = txt.index("welcome")
print(x)
op: 7
txt = "50800"
x = txt.isdigit()
print(x)
txt = "Company10"
x = txt.isalpha()
print(x)
txt = " banana "
x = txt.strip()
print("of all fruits", x, "is my favorite")
of all fruits banana is my favourite
myTuple = ("John", "Peter", "Vicky")
x = "#".join(myTuple)
print(x)
John#Peter#Vicky
txt = " banana "
x = txt.lstrip()
print("of all fruits", x, "is my favorite")
of all fruits banana is my favorite