0% found this document useful (0 votes)
104 views

11 Strings

Strings in Python are sequences of characters that can be manipulated using a variety of methods and operators. Strings can be created by enclosing characters in single quotes, double quotes, or triple quotes. Each character in a string can be accessed using indexing with square brackets, with the first character having an index of 0. Strings are immutable, so their values cannot be changed after creation. Common string operations include concatenation, repetition, membership testing, comparison, slicing, and using built-in functions and methods.

Uploaded by

krishthefish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

11 Strings

Strings in Python are sequences of characters that can be manipulated using a variety of methods and operators. Strings can be created by enclosing characters in single quotes, double quotes, or triple quotes. Each character in a string can be accessed using indexing with square brackets, with the first character having an index of 0. Strings are immutable, so their values cannot be changed after creation. Common string operations include concatenation, repetition, membership testing, comparison, slicing, and using built-in functions and methods.

Uploaded by

krishthefish
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 67

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])
'!'

#gives error as index is out of range


>>> print(str1[15])
IndexError: string index out of range
The index can also be an expression including variables and operators
but the expression must evaluate to an integer.
#an expression resulting in an integer index

#so gives 6th character of str1


>>> print(str1[2+4])
'W'

#gives error as index must be an integer


>>> print(str1[1.5])
TypeError: string indices must be integers
Python allows an index value to be negative also. Negative indices are
used when we want to access the characters of the string from right to
left.
Starting from right hand side, the first character has the index as -1 and
the last character has the index –n where n is the length of the string.

>>> print(str1[-1]) #gives first character from right


'!'
>>> print(str1[-12])#gives last character from right
'H'
An inbuilt function len() in Python returns the length of the string that is passed as
parameter. For example, the length of string str1 = 'Hello World!' is 12.
#gives the length of the string str1
>>> print(len(str1))
12
#length of the string is assigned to n
>>> n = len(str1)
>>> print(n)
12
#gives the last character of the string
>>> str1[n-1]
'!'
#gives the first character of the string
>>> str1[-n]
'H'
String is Immutable
A string is an immutable data type. It means that the contents of the string
cannot be changed after it has been created. An attempt to do this would lead
to an error.

>>> str1 = "Hello World!"


#if we try to replace character 'e' with 'a‘

>>> str1[1] = 'a'


TypeError: 'str' object does not support item assignment
String Operations
Concatenation
To concatenate means to join. Python allows us to join two strings
using concatenation operator plus which is denoted by symbol +.

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!‘

>>> print('W' in str1)


True

>>> 'Wor' in str1


True

>>> print('My' in str1)


False
The 'not in' operator also takes two strings and returns True if the first
string does not appear as a substring in the second string, otherwise
returns False.

>>> str1 = 'Hello World!'


>>> 'My' not in str1
True

>>> 'Hello' not in str1


False
String is a sequence of characters,which is
enclosed between either single (' ') or double
quotes (" "), python treats both single and
double quotes same.
Creating String
Creation of string in python is very easy.
e.g.
a=‘Computer Science'
b=“Informatics Practices“
Accessing String Elements
e.g.
('str-', 'Computer Sciene')
str='Computer Sciene' ('str[0]-', 'C')
print('str-', str) ('str[1:4]-', 'omp')
print('str[0]-', str[0]) ('str[2:]-', 'mputer Sciene')
print('str[1:4]-', str[1:4]) ('str *2-', 'Computer
print('str[2:]-', str[2:]) ScieneComputer Sciene')
print('str *2-', str OUTPUT ("str +'yes'-", 'Computer
*2 )
print("str +'yes'-", str Scieneyes')
+'yes')
1. Write a program that should perform the following tasks
2. After getting a word from the user, your program should use a
loop to print out each of the letters of the word. Just
remember that strings in Python start with element 0!.
Iterating/Traversing through string
Each character of the string can be accessed sequentially
C
for loop.
using o
m
p
e.g. u
t
e
r
str='Computer Sciene‘ OUTPUT
S
for i in str:
c
print(i) i

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”

Operator Description Example


+ Concatenation – to add two strings a + b = comp sc
* Replicate same string multiple times (Repetition) a*2 = compcomp

[] Character of the string a[1] will give o


[:] Range Slice –Range string a[1:4] will give omp
in Membership check p in a will give 1
not in Membership check for non availability M not in a will give 1
% Format the string

print ("My Subject is %s and class is %d" % ('Comp Sc', 11))

‘%s’ is used to inject strings similarly ‘%d’ for integers, ‘%f’ for


floating-point values, ‘%b’ for binary format. 
Triple Quotes
It is used to create string with multiple lines.

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

str.capitalize() To capitalize the string r=a.capitalize() will be “COMP”


str.title() Will return title case string
str.upper() Will return string in upper case r=a.upper() will be “COMP”
str.lower() Will return string in lower case r=a.upper() will be “comp”
will return the total count of
str.count() a given element in a string r=a.count(‘o’) will be 1

To find the substring r=a.find (‘m’) will be 2


str.find(sub) position(starts from 0
index)
Return the string with r=b.replace(‘my’,’your’) will
str.replace() replaced sub strings be ‘your comp’
String functions and methods
a=“comp”
Method Result Example
r=a.index(‘o
str.index() Returns index position of substring m’) will be 1
String consists of only alphanumeric characters r=a.isalnum()
str.isalnum() (no symbols) will return True
String consists of only alphabetic characters
str.isalpha() (no symbols)
str.islower() String’s alphabetic characters are all lower case
str.isnumeric() String consists of only numeric characters
str.isspace() String consists of only whitespace characters
str.istitle() String is in title case
str.isupper() String’s alphabetic characters are all upper case
String functions and methods
a=“comp”
Method Result Example

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’

Removes specific character from leading


str.strip(char) and trailing position

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).

>>> str1 = 'Hello World!'


#gives substring starting from index 1 to 4
>>> print(str1[1:5])
'ello‘

#gives substring starting from 7 to 9


>>> print(str1[7:10])
'orl‘

#index that is too big is truncated down to the end of the string
>>> print(str1[3:20])
'lo World!‘

#first index > second index results in an empty '' string


>>> print(str1[7:2])
If the first index is not mentioned, the slice starts from index.
#gives substring from index 0 to 4
>>> print(str1[:5])
'Hello'
If the second index is not mentioned, the slicing is done till the length
of the string.
#gives substring from index 6 to end
>>> print(str1[6:])
'World!'
The slice operation can also take a third index that specifies the ‘step size’. For
example, str1[n:m:k], means every kth character has to be extracted from the string
str1 starting from n and ending at m-1. By default, the step size is one.
>>> print(str1[0:10:2])
'HloWr'
>>> print(str1[0:10:3])
'HlWl'
Negative indexes can also be used for slicing.
#characters at index -6,-5,-4,-3 and -2 are sliced
>>> print(str1[-6:-1])
'World'
If we ignore both the indexes and give step size as -1
#str1 string is obtained in the reverse order
>>> print(str1[::-1])
'!dlroW olleH'
Traversing a String
We can access each character of a string or traverse a
string using for loop and while loop.
A) String Traversal Using for Loop:
B) String Traversal Using while Loop:
A) String Traversal Using for Loop:
>>> str1 = 'Hello World!'
>>> for ch in str1:
print(ch,end = '')

Hello World! #output of for loop

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:

>>> str1 = 'Hello World!'


>>> index = 0
#len(): a function to get length of string
>>> while index < len(str1):
print(str1[index],end = '')
index += 1
Hello World! #output of while loop
Here while loop runs till the condition index < len(str) is True, where index
varies from 0 to len(str1) -1.
String Methods and Built-in Functions
Handling Strings
Program 8-1 Write a program with a user defined function to count the number of times a
character (passed as argument) occurs in the given string.
def charCount(ch,st):
count = 0
for character in st:
if character == ch:
count += 1
return count
#end of function
st = input("Enter a string: ")
ch = input("Enter the character to be searched: ")
count = charCount(ch,st)
print("Number of times character",ch,"occurs in the string is:",count)
Program 2:- Write a program with a user defined function with string
as a parameter which replaces all vowels in the string with '*'.
def replaceVowel(st):
#create an empty string
newstr = ''
for character in st:
#check if next character is a vowel
if character in 'aeiouAEIOU':
#Replace vowel with *
newstr += '*'
else:
newstr += character
return newstr
#end of function
st = input("Enter a String: ")
st1 = replaceVowel(st)
print("The original String is:",st)
print("The modified String is:",st1)
Program 3 Write a program to input a string from the user and print it
in the reverse order without creating a new string.

st = input("Enter a string: ")


for i in range(-1,-len(st)-1,-1):
print(st[i],end='')
Program 4 Write a program which reverses a string passed as parameter
and stores the reversed string in a new string. Use a user defined function
for reversing the string.
#Function to reverse a string
def reverseString(st):
newstr = '' #create a new string
length = len(st)
for i in range(-1,-length-1,-1):
newstr += st[i]
return newstr
#end of function
st = input("Enter a String: ")
st1 = reverseString(st)
print("The original String is:",st)
print("The reversed String is:",st1)
Program 5 Write a program using a user defined function to check if a string is
a palindrome or not. (A string is called palindrome if it reads same backwards
as forward. For example, Kanak is a palindrome.)
def checkPalin(st):
i=0
j = len(st) - 1
while(i <= j):
if(st[i] != st[j]):
return False
i += 1
j -= 1
return True
#end of function
st = input("Enter a String: ")
result = checkPalin(st)
if result == True:
print("The given string",st,"is a palindrome")
else:
print("The given string",st,"is not a palindrome")

You might also like