U18CSI2201 - Strings 1

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 38

U18CSI2201 - PYTHON PROGRAMMING

UNIT – III

STRINGS, LISTS and SETS


Learning Objectives
• After undergoing this course the student able to
Source of Content
• http://nptel.ac.in
• https://
www.edx.org/course?search_query=Computing+in+Python+III%3A+D
ata+Structures
• https://www.w3resource.com/python/python-tutorial.php
Grading
What is String?
• In many languages, strings are arrays of characters.
• In python, string is an object of str class.
• This string class has many constructors.
Str Class
• Creating a string using the constructor of str class as:
S1=str() #Creates an Empty string object
S2=str(“Hello”) #Creates a string object for Hello
• Alternate method is by assigning a string value to a variable.
Eg:
S1=“” #Creates an Empty string
S2=“Hello” #Equivalent to S2=str(“Hello”)
Basic inbuilt python functions for String
Example:
>>>a=“PYTHON’’
>>>len(a) #return length
6
>>>min(a) #return smallest character
‘H’
>>>max(a) #return largest character
‘Y’
Index[] operator
• Access the characters one at a time with the bracket operator:
Example:
>>> fruit = 'banana'
>>> fruit[0] #Access the first element of the string.
‘b'
• The expression in brackets is called an index.
• The index indicates which character in the sequence you want.
b a n a n a
0 1 2 3 4 5
Accessing characters via negative index
• The negative index accesses characters from the end of a string by counting
in backward direction.
fruit =
b a n a n a
-6 -5 -4 -3 -2 -1
• The index of the last character of any non-empty string is always -1.
Example:
>>>fruit=“banana”
>>>fruit[-6] #Access the first element of the string.
‘b’
String slices
• The slicing operator returns a subset of a string called slice by
specifying two indices, start and end
Syntax:
String name[start_index:end_index]
Example:
>>>S=“IIT-BOMBAY”
>>>S[4:10]
‘BOMBAY’
String slicing with step size
Syntax:
String name[start_index:end_index:step_size]
Example:
>>>S=“IIT-BOMBAY”
>>>S[0:len(S):2]
‘ITBMA’
String slicing
Example 1:
>>>S=“IIT-MADRAS”
>>>S[::] #Prints the entire string
‘IIT-MADRAS’
Example 2:
>>>S=“IIT-MADRAS”
>>>S[::-1] #Displays the string in reverse order
‘SARDAM-TII’
String slicing
Example 3:
>>>S=“IIT-MADRAS”
>>>S[-1:0:-1] #Access the character of a string from index -1
‘SARDAM-TI’
Example 4:
>>>S=“IIT-MADRAS”
>>>S[:-1] #Start with index 0 and exclude last character
‘IIT-MADRA’
• Convert the first letter of the string into uppercase letter
x="rajan"
y=x[0].upper() + x[1:]
print(y)

• Convert the last letter of the string into uppercase letter


x="rajan"
y=x[0:len(x)-1] + x[-1].upper()
print(y)
• Convert the first and last letter of the string into uppercase letter
x="rajan"
y=x[0].upper()+x[1:len(x)-1] + x[-1].upper()
print(y)
Immutable strings
• Character sequences fall into two categories:
i) Mutable - changeable
ii) Immutable - unchangeable
• Strings are immutable sequences of characters.
Example:
str1=“I like Python”
str1[0]=“U”
print(str1)
Output:
error
Immutable strings
Example:
str1=“I like Python”
str2=“U”+str1[1:]
print(str2)
Output:
U like Python
String operations
String comparison
• Operators such as ==,<,>,<=,>= and != used
Example:
word="banana"
if word < 'banana':
print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.'
else:
print 'All right, bananas.'
Split() Method
• Returns a list of all words in a string
Example:
Str1=“c c++ java python
Str1.split()
Output:
[‘c, c++, java, python’]
Testing String
• Test if entered string is a digit bool isalpha() – Returns true
or alphabet or alphanumeric if characters are alphabetic
bool isalnum() – Returns true if Example:
characters are alphanumeric S=“python”
Example: S.isalpha()
S=“python” Output
S.isalnum() True
Output
True
Testing String
bool isdigit() – Returns true if bool islower() – Returns true
characters contain digits if characters are lowercase
Example: Example:
S=“1234” S=“python”
S.isdigit() S.islower()
Output Output
True True
Testing String
bool isupper() – Returns true if bool isspace() – Returns true
characters are uppercase if string contain white spaces
Example: Example:
S=“PYTHON” S=“ ”
S.isupper() S.isspace()
Output Output
True True
Searching substring in a string
bool endswith(str str1) - bool startswith(str str1) -
Returns true if string ends with Returns true if string starts
the substring str1 with the substring str1
Example: Example:
S=“Python Programming” S=“Python Programming”
S.startswith(“Python”)
S.endswith(“Programming”)
Output
Output True
True
Searching substring in a string
int find(str str1) - int count(str str1) -
Returns the index if string is Returns the number of
present occurrences of the substring
Example: Example:
S=“Python Programming” S=“good morning”
S.count(“o”)
S.find(“Prog”)
Output
Output 3
7
Methods to convert a string into another string
str capitalize() - str lower() -
Returns the string with first Returns the string with
letter capitalised lowercase
Example: Example:
S=“python” S=“INDIA”
S.lower()
S.capitalize()
Output
Output ‘india’
‘Python’
Methods to convert a string into another string
str title() - str upper() -
Returns the string with first Returns the string with
letter capitalised in each word uppercase
Example: Example:
S=“welcome to python” S=“india”
S.upper()
S.title()
Output
Output ‘INDIA’
‘Welcome To Python’
Methods to convert a string into another string
• remove whitespace at the greet = ' Hello Bob '
beginning and/or end greet.lstrip()
'Hello Bob '
• lstrip() and rstrip() to the greet.rstrip()
left and right only ' Hello Bob'
greet.strip()
• strip() Removes both begin
'Hello Bob'
and ending whitespace
'Hello Bob'
>>>
Programs
• Write the program to read the string and display ‘Total number of
uppercase and lowercase letters’
• Write a program to print the characters present at Odd Index and
even index positions in a String.
x= "I am Learning "
u=0
c=0
for i in x:
if i.isupper():
u+=1
elif i.islower():
c+=1
else:
pass

print("uppercase",u)
print("Lowercase",c)
Solution for Ex.2
def modify(string):
final_odd = ""
final_even="" Output:
for i in range(len(string)):
if i % 2 ==0: Enter string: kumaraguru
final_odd = final_odd+string[i]
else: String in odd and even index position is:
final_even=final_even+string[i] ('kmrgr', 'uaauu')

return final_odd, final_even

string=input("Enter string:")
print("String in odd and even index position is:")
print(modify(string))
# count the number of vowels

x = input("Enter the string ")


x= x.lower()
count =0
for i in x:
if i=='a' or i=='e' or i=='o' or i=='i' or i=='u':
count+=1
print(x)
print(count)

# Method 2
y=x.count('a') + x.count('e') + x.count('i') + x.count('o') +
x.count('u')
print(y)
# count the number of digits, alphabet, special char, word and sentence in the given paragraph
x = input("Enter the string ")
count,c,c1,p=0,0,0,0

for i in x:
if i.isalpha():
count= count + 1
elif i.isdigit():
c=c+1
elif i==".":
p=p+1
else:
c1 = c1 + 1
word = len(x.split())
print("Char",count)
print("Digit = ",c)
print("Spl=",c1)
print("Para",p)
print("word",word)
Quiz
1.What will be the output of the following:
s1= “Welcome to java programming”
s2=s1.replace(“java”,”python”)
print(s2)
a. Welcome to java programming
b. Welcome to python programming
c. Welcome to java python programming
d. None of the above
2. What will be the output of the following:
str1=“Hello”
str2=str1[:-1]
print(str2)

a.olle
b.Hello
c.el
d.Hell
3.What will be the output of the following:
str1=“Python Programming”
str1[0]=“J”
print(str1)

a. Jython Programming
b. Jython Jrogramming
c. Jython
d. Error
4.What will be the output of the following:
S=“Programming”
For char in S:
print(char, end=“ ”)

a.Programming
b.P r o g r a m m i n g
c.Error
d.None of the above
Summary
Creating String
Indexing strings
Slicing strings
Immutable strings
String operations

You might also like