[go: up one dir, main page]

0% found this document useful (0 votes)
8 views57 pages

Unit IV

Unit-IV

Uploaded by

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

Unit IV

Unit-IV

Uploaded by

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

UNIT: Strings Lectures:

IV 07 Hrs

• Strings and Operations:

• concatenation, appending, multiplication and slicing

• Strings are immutable, strings formatting operator, built in string methods


and functions.

• Slice operation, ord() and chr() functions, in and not in operators,

• comparing strings, Iterating strings

• the string module.

Savitribai Phule Pune University - 2019-20


Strings and Operations:

What is String?
 String is sequence of characters in the single or double or even
triple quotes.
 A character could be letter, digit, whitespace, or any other
symbol.

Ex: name="India"
graduate = 'N'
nationality = str("Indian")

Savitribai Phule Pune University - 2019-20


#Assign String to a Variable
name="India"
graduate = 'N'
nationality = str("Indian")

print("String is ",name)
print("type of name variable is ",type(name))
print("String is ",graduate)
print("String is ",nationality)

Output:
String is India
type of name variable is <class 'str'>
String is India
String is N
String is Indian
Savitribai Phule Pune University - 2019-20
Indexing and Traversing a string
 Individual characters in a string are accessed using the slice
[index] operator.

 The index specifies the character access from given string.


Index can be integer or expression.

 A string can be traversed by accessing character from first


character to last character.

Savitribai Phule Pune University - 2019-20


Program:
name="Akshay"
index=0
for i in name:
print("name[", index, "] = ", i)
index=index+1

Output:
name[ 0 ] = A
name[ 1 ] = k
name[ 2 ] = s
name[ 3 ] = h
name[ 4 ] = a
name[ 5 ] = y
 In example, there are 6 characters in the name, if we try to access 7th character by
print(name[6]) , then IndexError: string index out of range error
occurs. Savitribai Phule Pune University - 2019-20
Program:
str = "Hello, welcome to python"
i=2
print(str[i]) # i is expression
print(str[i*3+1]) # i*3+1 is expression

Output:
l
w

Savitribai Phule Pune University - 2019-20


Python - Slicing Strings
 You can return a range of characters by using the slice syntax
 Specify the start index and the end index, separated by a colon, to return a
part of the string.
 slicing operator [ ] can be used with string.
Ex: str = "hello"
print(str[:])
print(str[0:])
print(str[:5])
print(str[:3])
print(str[0:2])
print(str[1:4])
Output:
hello
hello
hello
hel
he
ell Savitribai Phule Pune University - 2019-20
Write a python program to change a given string to a new string where first and last
character have been exchanged.
(Input: Program Output: mrograP)

name = "Program"
first = name[-1:]
print(first)

middle = name[1:6]
print(middle)

last = name[0]
print(last)

print(first + middle + last)


Output:
m
rogra
P
mrograP

Savitribai Phule Pune University - 2019-20


2. Write a python program to remove nth index character from non
empty string.
name = input("enter the string")
n = int(input("Enter nth index character to be removed"))

first = name[:n]
print(first)

last = name[n+1:]
print(last)

print(first + last)

Output:
enter the string akshay
Enter nth index character to be removed 3
aks
ay
aksay

Savitribai Phule Pune University - 2019-20


Concatenation, Appending And Multiplication on strings:

1. Concatenation:
 Joining of two or more strings is called concatenation.
 + operator is used for concatenation.

Ex:
firstname = input("enter the first name: ")
lastname = input("enter the last name: ")
print("Concatenation is: ", firstname + lastname)

Output:
enter the first name: rahul
enter the last name: patil
Concatenation is: rahulpatil
Savitribai Phule Pune University - 2019-20
2. Appending string

Ex:
str = "Hello, "
name = input("Enter your name: ")
str += name #str=str+name
str += ". Welcome to python programming"
print(str)

Output:
Enter your name: Ajay
Hello, Ajay. Welcome to python programming

Savitribai Phule Pune University - 2019-20


3. Multiplication of string

 The * operator is used to repeat string for n number of times.

Ex:
str = "Welcome!“
print(str*3)

Output:
Welcome!Welcome!Welcome!

Savitribai Phule Pune University - 2019-20


String are Immutable
 Strings once created they can not be changed.
 Whenever you try to modify an existing string variable, a new string is
created.

Ex:
str = "Welcome!"
str[0]="p"
print(str)

Output:
'str' object does not support item assignment

Savitribai Phule Pune University - 2019-20


String formatting operator
 The format operator is specified using % operator.
 The % operator takes a format string on the left( %d, %s, %f etc) and
corresponding values in tuple on right.
Syntax:
“<format>” %(<values>)
Ex:
name = "akash"
age = 8
print("name is %s and age is %d" %(name, age))
print("name is %s and age is %d" %("Sakshi", 25))

Output:
name is akash and age is 8
name is Sakshi and age is 25

Savitribai Phule Pune University - 2019-20


Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Smt. Kashibai Navale College of Engg, Pune. Savitribai Phule Pune University - 2019-20
Built in string Methods and Functions
1. capitalize( )
 This method converts the first letter of string to capital.

Ex:
str = "welcome"

str2 = str.capitalize()

print("Old value:", str)


print("New value:", str2)

Output:
Old value: welcome
New value: Welcome

Savitribai Phule Pune University - 2019-20


2. count( )
 It returns number of times particular string appears in statement

Ex:
str = "twinkle twinkle little"

str2 = str.count("twinkle")
print(str2)

Output:
2

Savitribai Phule Pune University - 2019-20


3. center (width, fillchar)
 It returns string centered to a total width and filled with fillchar

Ex:
str = "India"
print(str.center(10,'*'))

Output:
**India***

Savitribai Phule Pune University - 2019-20


4. endswith (value)
 This method returns true if the string ends with specified value,
otherwise false.

Ex:
str = "India is the best country in the world!"
print(str.endswith("!"))

Output:
True

Savitribai Phule Pune University - 2019-20


5. find( )
 It returns index of first occurrence of substring

Ex:
str = "India is the best country in the world!"
print(str.find("the"))

Output:
9

Savitribai Phule Pune University - 2019-20


6. index( )
 It returns index of first occurrence of substring, if not found gives error.

Ex:
str = "India is the best country in the world!"
print(str.index("best"))

Output:
13

Savitribai Phule Pune University - 2019-20


7. isalpha( )
 It returns true if all the character in the string are alphabets, otherwise
false

Ex:
str = "JamesBond007"
print(str.isalpha())
str = "JamesBond"
print(str.isalpha())

Output:
False
True

Savitribai Phule Pune University - 2019-20


8. isdigit( )
 It returns true if all the characters in the string are digits.

Ex:
str = "1234"
print(str.isdigit())

Output:
True

Savitribai Phule Pune University - 2019-20


9. islower( )
 It returns true, if all the characters in the string are in lowercase letters

Ex:
str = "JamesBond"
print(str.islower())
str = "jamesbond"
print(str.islower())

Output:
False
True

Savitribai Phule Pune University - 2019-20


10. isupper( )
 It returns true, if all the characters in the string are in uppercase letters

Ex:
str = "INDIA IS GREAT"
print(str.isupper())
str = "India is Great "
print(str.isupper())

Output:
True
False

Savitribai Phule Pune University - 2019-20


11. isspace( )
 It returns true if string only contains whitespaces otherwise false

Ex:
str = " "
print(str.isspace())

Output:
True

Savitribai Phule Pune University - 2019-20


12. len( )
 It returns length of string or number of characters in string.

Ex:
str = "INDIA IS GREAT"
print(len(str))

Output:
14

Savitribai Phule Pune University - 2019-20


13. replace(old, new )
 It replaces old value with new value.

Ex:
str = "I love my country"
print(str.replace("country","India"))

Output:
I love my India

Savitribai Phule Pune University - 2019-20


14. lower( )
 It converts all the characters in string into lowercase.

Ex:
str = "INDIA IS GREAT"
print(str.lower())

Output:
india is great

Savitribai Phule Pune University - 2019-20


15. upper( )
 It converts all the characters in string into uppercase.

Ex:
str = "I love my country"
print(str.upper())

Output:
I LOVE MY COUNTRY

Savitribai Phule Pune University - 2019-20


16. lstrip( )
 It removes all leading left whitespaces of the string.

Ex:
str = " India "
print(str.lstrip()+"is a country")

Output:
India is a country

Savitribai Phule Pune University - 2019-20


17. rstrip( )
 It removes all trailing right whitespaces of the string.

Ex:
str = " India "
print(str.rstrip()+"is a country")

Output:
Indiais a country

Savitribai Phule Pune University - 2019-20


18. strip( )
 It removes all leading and trailing whitespaces of the string.

Ex:
str = " India "
print(str.strip()+"is a country")

Output:
Indiais a country

Savitribai Phule Pune University - 2019-20


19. max( )
 It returns highest alphabetical character.

Ex:
str = "country"
print(max(str))

Output:
y

Savitribai Phule Pune University - 2019-20


20. min( )
 It returns lowest alphabetical character.

Ex:
str = "country"
print(min(str))

Output:
c

Savitribai Phule Pune University - 2019-20


21. title( )
 It returns first letter of string to uppercase.

Ex:
str = "python is easy to learn"
print(str.title())

Output:
Python Is Easy To Learn

Savitribai Phule Pune University - 2019-20


22. split( )
 It splits the string at specified separator and returns list.

Ex:
str = "python#is#easy#to#learn"
print(str.split("#"))

Output:
['python', 'is', 'easy', 'to', 'learn']

Savitribai Phule Pune University - 2019-20


23. swapcase( )
 Uppercase character becomes lowercase and viceversa.

Ex:
str = "Python Is Easy To Learn"
print(str.swapcase())

Output:
pYTHON iS eASY tO lEARN

Savitribai Phule Pune University - 2019-20


24. zfill( )
 This method adds zero at the beginning of the string until it reaches the
specified length.

Ex:
str = "Python"
print(str.zfill(10))

Output:
0000Python

Savitribai Phule Pune University - 2019-20


ord ( ) and chr ( ) function:
 The ord( ) function returns the ASCII code of the character.
 The chr( ) function returns the character represented by the ASCII code.
 ASCII, abbreviated from American Standard Code for Information
Interchange, is a character encoding standard for electronic
communication. ASCII codes represent text in computers,
telecommunications equipment, and other devices.

Ex: Ex:
ch = 'a' print(chr(90))
print(ord(ch)) Output:
Output: Z
97

Savitribai Phule Pune University - 2019-20


Membership Operators(in, not in operators):
 in and not in operator are called membership operator.
 These operators can be used to determine whether a string is present in
another string or not

Ex: Ex:
str1 = "Python program is fun" str1 = "Python program is fun"
str2 = "fun" str2 = "fun"

if str2 in str1: if str2 not in str1:


print("Present") print("Present")
else: else:
print("Not present") print("Not present")

Output: Output:
Present Not Present

Savitribai Phule Pune University - 2019-20


Comparing strings:
 Python allows you to compare strings using relational (or comaparison)
operators (<, >, <=, >= etc.)

 Comparing string is done by using lexicographical order i.e. using


ASCII value of the character.

 The ASCII value of character A-Z is 65-90 and ASCII value of


character a-z is 97-122. This means book is greater than Book because
the ASCII value of ‘b’ is 98 and ‘B’ is 66.

Savitribai Phule Pune University - 2019-20


Savitribai Phule Pune University - 2019-20
Iterating Strings:
 String is sequence of characters.
 We can traverse or iterate string using for loop or while loop.

Ex: using for loop Ex: using while loop

str = "Welcome to Python" str = "Welcome to Python"


i = 0
for i in str: while(i < len(str)):
print(i, end=" ") print(i, end=" ")
i = i+1

Output: Output:
W e l c o m e t o P y t h o n W e l c o m e t o P y t h o n

Savitribai Phule Pune University - 2019-20


1. Write a python program to accept string and display reverse string.
str = "Welcome"
rev = " "
for i in str:
rev = i + rev

print("Original String is:", str)


print("Reversed string is:", rev)
Output:
Original String is: Welcome
Reversed string is: emocleW

Savitribai Phule Pune University - 2019-20


2. Write a python program to display how many times particular letter
appears in string.
str = "Welcome to India"
count = 0

letter = input("Enter the letter to search in string: ")

for i in str:
if i == letter:
count = count + 1

print("Letter ",letter,"appears in string",count,"times")

Output:
Enter the letter to search in string: o
Letter o appears in string 2 times

Savitribai Phule Pune University - 2019-20


3. Write a python program to check whether a string is Palindrome or
Not.
str = 'POP'

# reverse the string


revstr = reversed(str)

# check if the string is equal to its reverse


if list(str) == list(revstr):
print("It is palindrome")
else:
print("It is not palindrome")

Output:
It is palindrome

Savitribai Phule Pune University - 2019-20


4. Write a python program to sort a word in string in alphabetical order.

my_str = input("Enter a string: ")

# breakdown the string into a list of words


words = my_str.split()

# sort the list Output:


words.sort() Enter a string:
Hi Akash Welcome To Python
# display the sorted words The sorted words are:
print("The sorted words are:") Akash
for word in words: Hi
print(word) Python
Welcome
To

Savitribai Phule Pune University - 2019-20


String Module
 The string module contains number of constants and functions to process the
standard python strings.
 To use the string module in python we need to import it at the beginning.

Functions:
1. capwords ( ):
 This function converts first letter of the string into capital letters.
Ex:
import string
str = "I love python programming"
print("Original string is: "+str)
print("After convert : "+string.capwords(str))
Output:
Original string is: I love python programming
After convert : I Love Python Programming

Savitribai Phule Pune University - 2019-20


2. Methods used in string(upper, lower, split, join, count, replace, and find)

 str.upper( ) is used to convert given string to upper case letter.

 str.lower( ) is used to convert given string to lower case letter.

 str.split( ) is used to split the given string.

 str.join( ) is used to join the splitted string.

 str.replace( ) is used to replace the old value in string with


new value.

 str.find( ) is used to find index of substring in string.


Savitribai Phule Pune University - 2019-20
Ex:
str1 = "Welcome to world of Python"
print("upper case: "+str1.upper())
print("lower case: "+str1.lower())
print(str1.split())
print('-'.join(str1.split()))
print("Replace is: "+str1.replace("Python","Java"))
print(str1.count("o"))
print(str1.find("of"))

Output:
upper case: WELCOME TO WORLD OF PYTHON
lower case: welcome to world of python
['Welcome', 'to', 'world', 'of', 'Python']
Welcome-to-world-of-Python
Replace is: Welcome to world of Java
5
17
Savitribai Phule Pune University - 2019-20
3. Constants defined in string literals:
Constant Value

string.ascii_letters ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ’
string.ascii_lowercase ‘abcdefghijklmnopqrstuvwxyz’
string.ascii_uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
string.digits ‘0123456789’
string.hexdigits ‘0123456789abcdefABCDEF’
string.letters ‘abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP
QRSTUVWXYZ’
string.lowercase ‘abcdefghijklmnopqrstuvwxyz’
string.Octdigits ‘01234567’
string.punctuation ‘!@#$%^&*( )_+-=<>?{}[]|\;:”
string.uppercase ‘ABCDEFGHIJKLMNOPQRSTUVWXYZ’
string.whitespace ‘\t\n\x0b\x0c\r’

Savitribai Phule Pune University - 2019-20


Ex:
import string

print("Letters : ", string.ascii_letters)


print("Letters : ", string.ascii_lowercase)
print("Letters : ", string.ascii_uppercase)
print("Letters : ", string.digits)
print("Letters : ", string.hexdigits)
print("Letters : ", string.punctuation)
print("Letters : ", string.octdigits)

Output:
Letters :
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Letters : abcdefghijklmnopqrstuvwxyz
Letters : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Letters : 0123456789
Letters : 0123456789abcdefABCDEF
Letters : !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Letters : 01234567
Savitribai Phule Pune University - 2019-20
1. Write a python program to count digits and letters and symbols in
given string.
str = input("Enter the string:")
digit = 0
letter = 0
symbols = 0
for i in str:
if (i.isdigit()):
digit += 1
elif(i.isalpha()):
letter += 1
else:
symbols += 1

print("Original string is :", str)


print("Total number of digit in string is:",+digit)
print("Total number of letters in string is: ",+letter)
print("Total number of symbols in string is: ",+symbols)

Savitribai Phule Pune University - 2019-20


Output:
Enter the string: Python!@123
Original string is: Python!@123
Total number of digit in string is: 3
Total number of letters in string is: 6
Total number of symbols in string is: 2

Savitribai Phule Pune University - 2019-20


3. Write a python program to check if a substring is present in given
string or not.

str = input("Enter the string:")


str1 = input("Enter the substring to search: ")

if(str.find(str1) == -1):
print("Substring is not present in given string")
else:
print("Substring is present in given string ")

Output:
Enter the string: Sky blue
Enter the substring to search: blue
Substring is present in given string

Savitribai Phule Pune University - 2019-20

You might also like