11 Strings
11 Strings
STRINGS
String is a sequence which is made up of one or more UNICODE characters. Here the
character can be a letter, digit, whitespace or any other symbol. A string can be created by
enclosing one or more characters in single, double or triple quote.
>>> str1 = 'Hello World!'
>>> str2 = "Hello World!"
>>> str3 = """Hello World!"""
>>> str4 = '''Hello World!'‘
Values stored in str3 and str4 can be extended to multiple lines using triple codes as can be
seen in the following example:
>>> str3 = """Hello World!
welcome to the world of Python"""
>>> str4 = '''Hello World!
welcome to the world of Python'''
Python does not have a character data type.
String of length one is considered as
character.
Accessing Characters in a String
Each individual character in a string can be accessed using a technique called
indexing.
The index specifies the character to be accessed in the string and is written in
square brackets ([ ]).
The index of the first character (from left) in the string is 0 and the last
character is n-1 where n is the length of the string. It starts from 0 and ends
on n-1.
If we give index value out of this range then we get an IndexError. The index
must be an integer (positive, zero or negative).
#initializes a string str1
>>> str1 = 'Hello World!'
#gives the first character of str1
>>> print(str1[0])
'H'
#gives seventh character of str1
>>> print(str1[6])
'W'
#gives last character of str1
>>> print(str1[11])
'!'
fname=“Radhika”
lname=“Shanti”
fullName=fname +lname
print(fullName)
Repetition
Python allows us to repeat the given string using repetition operator which is denoted by
symbol *.
#assign string 'Hello' to str1
>>> str1 = 'Hello'
#repeat the value of str1 2 times
>>> print(str1 * 2)
'HelloHello'
#repeat the value of str1 5 times
>>> print(str1 * 5)
'HelloHelloHelloHelloHello'
Note: str1 still remains the same after the use of repetition operator.
Membership
Python has two membership operators 'in' and 'not in'. The 'in' operator takes two strings
and returns True if the first string appears as a substring in the second string, otherwise it
returns False.
>>> str1 = 'Hello World!‘
e
Print out each of the letter in reverse order.
Make a new variable that is the original word reverse
and print variable.
1.Code to count the number of occurrence of a
Character in String.
String comparison
We can use ( > , < , <= , <= , == , != ) to compare two strings.
Python compares string lexicographically i.e using ASCII value
of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj" . The first
two characters from str1 and str2 ( M and M ) are compared. As
they are equal, the second two characters are
compared. Because they are also equal, the third two
characters ( r and n ) are compared. And because 'r' has
greater ASCII value than ‘n' , str1 is greater than str2 .
e.g.program
OUTPUT
print("Maria" == "Manoj") False
print("Maria" != "Manoj") True
print("Maria" > "Manoj") True
print("Maria" >= "Manoj") True
print("Maria" < "Manoj")
print("Maria" <= "Manoj") False
print("Maria" > "")
False
True
1.Write a loop that prints out the index of every ‘i’ in
‘Mississippi’.
Updating Strings
String value can be updated by reassigning another
value
in it.
e.g.
var1
=
'Co
mp
Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )
OUTPUT
('Updated String :- ', 'Comp Sc
with Python')
String Special Operators
e.g.
a=“comp” b=“sc”
e.g.
Str1 = “””This course will introduce the learner to
text mining and text manipulation basics. The
course begins with an understanding of how text
is handled by python”””
String functions and methods
a=“comp”
b=“my comp”
Method Result Example
Returns the length of
len() the string r=len(a) will be 4
b=‘**comp’;
str.lstrip(char) Returns a copy of the string with leading/trailing r=b.lstrin()
str.rstrip(char) characters removed will be ‘comp’
b=‘my comp’;
r=b.split() will
str.split() Returns list of strings as splitted be [‘my’,‘comp’]
b=‘my comp’;
r=b.partition(‘
str.partition() Partition the string on first occurrence of substring co mp’) will be
[‘my’,‘comp’]
#Python Program to calculate the number of
digits
and letters in a string
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number
of digits is:")
print(count1)
print("The number of characters
Searching for Substrings
METHODS E.g. program
METHOD NAME DESCRIPTION:
endswith(s1: str): bool Returns True if strings s = "welcome to python"
ends with substring s1 print(s.endswith("thon"))
startswith(s1: str): bool Returns True if strings starts with print(s.startswith("good"))
substring s1 print(s.find("come"))
count(substring): int Returns number of occurrences of print(s.find("become"))
substring the string print(s.rfind("o"))
print(s.count("o"))
find(s1): int Returns lowest index from where
s1 starts in the string, if string
not found returns -1 OUTPUT
True False
3
rfind(s1): int Returns highest index from
where s1 starts in the string, if -1
string not found returns -1 15
3
1.Using endswith() and startwith() function print the
character used in the start and end of a string.
Slicing
In Python, to access some part of a string or substring, we use a method called slicing.
This can be done by specifying an index range. Given a string str1, the slice operation str1[n:m] returns the part of the string
str1 starting from index n (inclusive) and ending at m (exclusive).
In other words, we can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1].
The numbers of characters in the substring will always be equal to difference of two indices m and n, i.e., (m-n).
#index that is too big is truncated down to the end of the string
>>> print(str1[3:20])
'lo World!‘
In the above code, the loop starts from the first character of the string str1 and
automatically ends when the last character is accessed.
(B) String Traversal Using while Loop: