0% found this document useful (0 votes)
32 views19 pages

Unit 4 STRINGS

Uploaded by

Nainesh Salunke
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)
32 views19 pages

Unit 4 STRINGS

Uploaded by

Nainesh Salunke
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/ 19

Unit-IV

STRINGS
Concept of String:
 String is basically the sequence of characters.
 Any desired character can be accessed using the index.
>>> country="India"
>>> country[1]
'n'
>>> country[2]
'd'
 The strings can be created using single, double or triple quotes.
 Example:
>>> msg='Good Bye'
>>> msg
'Good Bye'
>>> msg="Good Bye"
>>> msg
'Good Bye'
>>> msg='''Good Bye'''
>>> msg
'Good Bye'

String Operations
1. Finding Length of string:
o There is an in-built function to find length of string.
o This is len function.
Example:
>>> msg="Good bye"
>>> len(msg)
Output:
8
2. Concatenation:
 Joining of two or more strings is called concatenation.
 In python we use + operator for concatenation of two strings.
Example:
>>> str1="Python"
>>> str2="Program"
>>> str3=str1+str2
>>> print(str3)
Output:
PythonProgram
3. Appending:
 We can use += operator to append some string to already existing string.
 Example:
>>> str1="Python programming is fun"
>>> str1+="we enjoy it very much"
>>> print(str1)
Output:
Python programming is fun.we enjoy it very much
4. Multiplying strings:
 The * operator is used to repeat the string for n number of times.
 Example:
>>> str="welcome"
>>> print(str*3)
Output:
welcomewelcomewelcome
>>> print(str*5)
Output:
welcomewelcomewelcomewelcomewelcome
Strings are Immutable
 Strings are immutable i.e. we cannot change the existing strings.
 Example:
>>> msg="Good Morning"
>>> msg[0]='g'
Output:
TypeError: 'str' object does not support item assignment

String Formatting Operator:


 The format operator is specified using % operator.
 It act as interface between the format specifiers and their values.
 That means it binds the format specifiers to the values.
 Format specifiers for different data types are as follows.
 %d-integer %f-float %s-string
 %x-hexadecimal %o-octal
 Example 1:
>>> 'There are %d colors in a rainbow'%7
'There are 7 colors in a rainbow'
>>> 'I like %s color'%'blue'
'I like blue color'
>>> 'There are %d letters in the word %s'%(4,'blue')
'There are 4 letters in the word blue'
>>> 'The value of %s is %f'%('PI',3.14)
'The value of PI is 3.140000'

 Example 2:
>>> I=30
>>> Float=3.14
>>> String="Rahul“
>>> print("Integer value:%d"%I)
Integer value:30
>>> print("Float Value:%f"%Float)
Float Value:3.140000
>>> print("String Value:%s"%String)
String Value:Rahul

 Example 3:
Program for addition of two numbers
>>> a=10
>>> b=20
>>> c=a+b
>>> print("Addition is %d“%c)
Addition is 30

 Example 4:
Program for square of number
print("Enter the number:")
n=int(input())
square=n*n
print("Square of number is %d"%square)
Enter the number:
5
Square of number is 25
Example 5:
Write a python program to display the name of the student, his course and
age.
name="Rahul"
Course="Computer Engineering"
age=18
print("Name=%s and course=%s and age=%d"%(name,Course,age))
print("Name=%s and course=%s and age=%d"%('Sachin','Mechanical
Engineering',20))
Output
Name=Rahul and course=Computer Engineering and age=18
Name=Sachin and course=Mechanical Engineering and age=20

Slice Operation:
 String slice is an extracted chunk of characters from the original string.
 In python we can obtain the string slice with the help of string indices.
>>> msg="Good Morning"
>>> msg[0:4]
'Good‘
 Here the string from 0 to less than 4 index will be displayed.
>>> msg[5:12]
'Morning'
 Here the string from 5th index to 11th index is displayed.
 We can omit the beginning index. In that case, the beginning index is considered as 0
>>> msg[:4]
'Good‘
 Similarly we can omit ending index. In that case, the string will be displayed up to its
ending character.
>>> msg[5:]
'Morning‘
 If we do not specify any starting index or ending index then the string from starting
index 0 to ending index character is considered.
>>> msg[:]
'Good Morning'
Example:
 Write python program to remove nth index character from non empty string.
def remove_ch(str,n):
first_part=str[:n] #taking slice upto nth character
last_part=str[n+1:] #skipping nth char and taking the slice of string of
remaining part
return first_part+last_part #joining two slices
print("Enter the some string")
str=input()
print("Enter index of character to be removed")
n=int(input())
print(remove_ch(str,n))
Output:
Enter the some string
python
Enter index of character to be removed
3
Pyton
Example:
Write python program to change a given string to a new string where first and last
characters have been exchanged
def interchange_char(str1):
return new_str[-1:]+new_str[1:-1]+new_str[:1]
print("Enter the string:")
new_str=input()
print(interchange_char(new_str))
Output:
Enter the string:
program
mrograp
Built in string Methods and Functions
1. capitalize (): This method converts the first letter of the string to capital.
Example:
str="i like python programming very much."
>>> msg=str.capitalize()
>>> print(msg)
Output:
I like python programming very much.
2. count (): It returns the number of times particular string appears in the statement .
Example:
>>> str="twinkle,twinkle little star, How I wonder what you are"
>>> msg=str.count("twinkle")
>>> print(msg)
Output:
2
3. center(width,fillchar): This method returns centered in a string of length width. Padding
is done using the specified fillchar.
Example:
>>> str="India"
>>> print(str.center(20,"#"))
Output:
#######India########
>>> print(str.center(18,"#"))
Output:
######India#######
4. endswith(value,start,end): This method true if the string ends with specified value,
otherwise false.
Example:
>>> str="India is best country in the world!"
>>> print(str.endswith("!"))
output:
True
>>> print(str.endswith("?"))
output:
False
5. find(): It returns the index of first occurrence of substring.
Example:
>>> str="I scream,you scream,we all scream for the icecream"
>>> print(str.find("scream"))
Output:
2
>>> print(str.find("we"))
Output:
20
6. index(): It searches the string for specified value and returns the positions of where it was
found.
Example:
>>> str="Sometimes later become never.Do it now."
>>> print(str.index("later"))
Output:
10
>>> print(str.index("never"))
Output:
23
7.isalpha(): It returns true if all the characters in the string are alphabets.
Example:
str="India"
>>> print(str.isalpha())
Output:
True
>>> str="I123dia"
>>> print(str.isalpha())
Output:
False
8.isdecimal(): It returns true if all the characters in the string are decimal(0-9).
Example:
>>> s="1234"
>>> print(s.isdecimal())
Output:
True
>>> t="abc1234"
>>> print(t.isdecimal())
Output:
False
9. islower(): It returns true if all the characters of the string are in lowercase.
Example:
>>> s="india is a great"
>>> print(s.islower())
Output:
True
>>> t="I Love my Country"
>>> print(t.islower())
Output:
False
10.isupper(): It returns true if all the characters of the string are in uppercase.
Example:
>>> s="INDIA IS GREAT"
>>> print(s.isupper())
Output
True
>>> t="I Love my Country"
>>> print(t.isupper())
Output
False
11.len(): It returns length of the string or number of characters in the string..
Example:
>>> str="I love my country"
>>> print(len(str))
Output
17
12.replace(): It replaces one specific phrase by some another specified phrase.
Example:
>>> str="I love my country"
>>> print(str.replace("country","India"))
Output:
I love my India
13. lower(): It converts all characters into the string to lowercase.
Example:
>>> str="I LOVE MY COUNTRY"
>>> print(str.lower())
Output:
i love my country
14. upper(): It converts all characters into the string to uppercase.
Example:
>>> str="i love my country"
>>> print(str.upper())
Output:
I LOVE MY COUNTRY
15. lstrip(): It removes all leading whitespaces of the string..
Example:
>>> str=" India "
>>> print(str.lstrip()+"is a country")
Output
India is a country
16. rstrip(): It removes all trailing whitespaces of the string..
Example:
>>> str=" India "
>>> print(str.rstrip()+"is a country")
Output:
Indiais a country
17. strip(): It removes all leading and trailing whitespaces of the string..
Example:
>>> str=" India "
>>> print(str.strip()+"is a country")
Output:
Indiais a country
18. max(): It returns highest alphabetical character.
Example:
>>> str="zebracrossing"
>>> print(max(str))
Output:
z
19. min(): It returns lowest alphabetical character.
Example:
>>> str="zebracrossing"
>>> print(min(str))
output:
a
20. title(): It returns first letter of the string to uppercase.
Example:
>>> str="python is easy to learn"
>>> print(str.title())
Output:
Python Is Easy To Learn
21.split(): This function splits the string at specified separator and returns a list.
Example:
>>> str="python#is#easy#to#learn"
>>> print(str.split('#'))
Output:
['python', 'is', 'easy', 'to', 'learn']
22.isspace(): Check if all the characters in the text are whitespaces
Example:
>>> str=" "
>>> print(str.isspace())
Output
True
>>> str=" s "
>>> print(str.isspace())
Output
False
23. isdigit(): It returns true if all the characters in the string are digits.
Example:
>>> s="12345"
>>> print(s.isdigit())
Output
True
>>> t="123abc"
>>> print(t.isdigit())
Output
False

ord() and chr() Functions


 The ord() function returns the ASCII code of character.
print(ord('a')) output: 97
print(ord('A')) output: 65
print(ord('B')) output:66
 The chr() function returns character represented by the ASCII CODE.
print(chr(65)) output: A
print(chr(66)) output: B
print(chr(97)) output: a
The in and not in Operators
 The in and not in are called membership operators.
 These operators are used to determine if the string is a member of another string or
not.
 Example that uses in operator
str1='Python programming is a fun'
str2='fun'
if str2 in str1:
print(str2,"is present in given string")
else:
print(str2,"is not present in given string")
Output:
fun is present in given string

 Example that uses not in operator


str1='Python programming is a fun'
str2=‘worry'
if str2 not in str1:
print(str2,"is not present in given string")
else:
print(str2,"is present in given string")
Output:
worry is not present in given string

Iterating strings
 We can traverse the string using the for loop or using while loop.
 Example:
 Write a program in python to traverse through string using while loop.
msg="Goodbye"
index=0
while index<len(msg):
letter=msg[index]
print(letter)
index=index+1
Output:
G
o
o
d
b
y
e

 Example:
 Write a program in python to traverse through string using for loop.
msg="Goodbye"
index=0
for index in range(0,len(msg)):
letter=msg[index]
print(letter)
Output:
G
o
o
d
b
y
e

 Write a program in python to display how many times particular letter appears
in the string.
def fun():
str='aaabbbccddeecccddd'
count=0
for i in str:
if i=='b':
count=count+1
print("The string is",str,"in which letter b appears",count,"times")
fun()
Output:
The string is aaabbbccddeecccddd in which letter b appears 3 times

 Write a program in python to find the length of a string.


def str_length(str):
len=0
for ch in str:
len=len+1
return len
print("Enter some string")
str=input()
print("length of string is:",str_length(str))
Output:
Enter some string
python
length of string is: 6

The string Module


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

Functions:
 There are some useful function used in string module.
1. The capwords function to display first letter capital:
 The capwords is function that converts first letter of the string into capital letter.
 Syntax:
string.capwords(string)
 Example
import string
str="i love python programming"
print(str)
print(string.capwords(str))
Output:
i love python programming
I Love Python Programming
2. The upper function and lower case:
 For converting the given string into upper case letter we have to use str.upper()
function and str.lower() function is for converting the string into lower case.
 Example
import string
text1="i love python programming"
text2="PROGRAMMING IN PYTHON IS REALLY INTERESTING"
print("Original string:",text1)
print("String in upper case:",str.upper(text1))
print("Original string:",text2)
print("String in lower case:",str.lower(text2))
Output:
Original string: i love python programming
String in upper case: I LOVE PYTHON PROGRAMMING
Original string: PROGRAMMING IN PYTHON IS REALLY INTERESTING
String in lower case: programming in python is really interesting
3. Translation of character to other form:
o The maketrans() returns the translation table for passing to translate(), that will
map each character in from_ch into the character at the same position in to_ch.
The from_ch and to_ch must have the same length.
o Syntax:
String.maketrans(from_ch,to_ch)
 Example
import string
from_ch="aeo"
to_ch="012"
str="I love programming in python"
print(str)
new_str=str.maketrans(from_ch,to_ch)
print(str.translate(new_str))
Output:
I love programming in python
I l2v1 pr2gr0mming in pyth2n

Constants:
 There are various constants defined in string module. We can display the values
of these string constant in python program.
 Example:
import string
print("Program to display string module constant")
print("Letters:",string.ascii_letters)
print("Lower case letters:",string.ascii_lowercase)
print("Upper case letters:",string.ascii_uppercase)
print("Digits:",string.digits)
print("Hexadigits:",string.hexdigits)
print("Punctuation:",string.punctuation)
Output:
Program to display string module constant
Letters: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
Lower case letters: abcdefghijklmnopqrstuvwxyz
Upper case letters: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits: 0123456789
Hexadigits: 0123456789abcdefABCDEF
Punctuation: !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

You might also like