Chapter 5 Python
Chapter 5 Python
Eg:
s="abab"
s1=s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
……………………………………………………………………………………….
Output:
abab is available at : 4568672
bbbb is available at : 4568704
……………………………………………………………………………………
In the above example, original object is available and we can
see new object which was created because of replace()
method.
…………………………………………………………………………………………..
*****************Splitting of Strings:**************:-
…………………………………………………………………………………………
We can split the given string according to specified seperator
by using split() method.
l=s.split(seperator)
Eg:
t=('sunny','bunny','chinny')
s='-'.join(t) print(s)
…………………………………………………………………………….
Output: sunny-bunny-chinny
……………………………………………………………………………………….
Eg2:
l=['bangalore','singapore','london','dubai']
s=':'.join(l)
print(s)
……………………………………………………………………………………….
bangalore:singapore:london:dubai
…………………………………………………………………………………………..
***************Changing case of a String:***********:-
………………………………………………………………………………………….
We can change case of a string by using the following 4
methods.
1. upper()===>To convert all characters to upper case
2. lower() ===>To convert all characters to lower case
3. swapcase()===>converts all lower case characters to upper
case and all upper case characters to lower case
4. title() ===>To convert all character to title case. i.e first
character in every word should be upper case and all
remaining characters should be in lower case.
5. capitalize() ==>Only first character will be converted to
upper case and all remaining characters can be converted to
lower case
………………………………………………………………………………………………
Eg:
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
…………………………………………………………………………………
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING PYTHON IS VERY EASY
Learning Python Is Very Easy
Learning python is very easy
……………………………………………………………………………………………
******Checking starting and ending part of the string:***:-
………………………………………………………………………………………….
Python contains the following methods for this purpose
1. s.startswith(substring)
2. s.endswith(substring)
……………………………………………………………………………………………
Eg:
s='learning Python is very easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))
…………………………………………………………………………………………
Output:
True
False
True
…………………………………………………………………………………………..
***To check type of characters present in a string:*****
…………………………………………………………………………………………..
Python contains the following methods for this purpose.
1) isalnum(): Returns True if all characters are alphanumeric(
a to z , A to Z ,0 to9 )
2) isalpha(): Returns True if all characters are only alphabet
symbols(a to z,A to Z)
3) isdigit(): Returns True if all characters are digits only( 0 to
9)
4) islower(): Returns True if all characters are lower case
alphabet symbols
5) isupper(): Returns True if all characters are upper case
aplhabet symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces
…………………………………………………………………………………………….
Eg:
print('prasanna786'.isalnum()) #True
print('prasanna786'.isalpha()) #False
print('prasanna'.isalpha()) #True
print('prasanna'.isdigit()) #False
print('786786'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle()) #True
print(' '.isspace()) #True
……………………………………………………………………………………………..
Demo Program:
1) s=input("Enter any character:")
2) if s.isalnum():
3) print("Alpha Numeric Character")
4) if s.isalpha():
5) print("Alphabet character")
6) if s.islower():
7) print("Lower case alphabet character")
8) else:
9) print("Upper case alphabet character")
10) else:
11) print("it is a digit")
12) elif s.isspace():
13) print("It is space character")
14) else:
15) print("Non Space Special Character")
……………………………………………………………………………………….
D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
……………………………………………………………………………………..
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character Alphabet character
Lower case alphabet character
……………………………………………………………………………………
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
……………………………………………………………………………………
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
………………………………………………………………………………..
***************Formatting the Strings:*********:-
………………………………………………………………………………….
We can format the strings with variable values by using
replacement operator {} and format() method.
Eg:
name='prasanna'
salary=10000
age=28
print("{} 's salary is {} and his age is
{}".format(name,salary,age))
print("{0} 's salary is {1} and his age is
{2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is
{z}".format(z=age,y=salary,x=name))
………………………………………………………………………………………..
Output:
prasanna 's salary is 10000 and his age is 28
prasanna's salary is 10000 and his age is 28
prasanna's salary is 10000 and his age is 28
………………………………………………………………………………….
****Important Programs regarding String Concept****:-
…………………………………………………………………………………………
Q1. Write a program to reverse the given String :-
input: prasanna
output:annasarp
…………………………………………………………..
1st Way:
s=input("Enter Some String:")
print(s[::-1])
……………………………………………………..
2nd Way:
…………………………
s=input("Enter Some String:")
print(''.join(reversed(s)))
…………………………………….
3rd Way:
……………………………………………………
s=input("Enter Some String:")
i=len(s)-1
target=''
while i>=0:
target=target+s[i]
i=i-1
print(target)
……………………………………………………………………………………..
Q. Write a program to print characters at odd position and
even position for the given String?
1st Way:
s=input("Enter Some String:")
print("Characters at Even Position:",s[0::2])
print("Characters at Odd Position:",s[1::2])
…………………………………………………………………………………….
Case-2: Formatting Numbers
d--->Decimal Integer
f----->Fixed point number(float).The default precision is 6
b-->Binary format
o--->Octal Format
x-->Hexa Decimal Format(Lower case)
X-->Hexa Decimal Format(Upper case)
………………………………………………………………………………………………
Eg-1:
print("The integer number is: {}".format(123))
print("The integer number is: {:d}".format(123))
print("The integer number is: {:5d}".format(123))
print("The integer number is: {:05d}".format(123))
Output:
The integer number is: 123
The integer number is: 123
The integer number is: 123
The integer number is: 00123
………………………………………………………………………………………………
Eg-2:
print("The float number is: {}".format(123.4567))
print("The float number is: {:f}".format(123.4567))
print("The float number is: {:8.3f}".format(123.4567))
print("The float number is: {:08.3f}".format(123.4567))
print("The float number is: {:08.3f}".format(123.45))
print("The float number is: {:08.3f}".format(786786123.45))
Output:
The float number is: 123.4567
The float number is: 123.456700
The float number is: 123.457
The float number is: 0123.457
The float number is: 0123.450
The float number is: 786786123.450
Note:
{:08.3f}
Total positions should be minimum 8.
After decimal point exactly 3 digits are allowed.
If it is less then 0s will be placed in the last positions
If total number is < 8 positions then 0 will be placed in MSBs
If total number is >8 positions then all integral digits will be
considered. The extra digits we can take only 0
Note: For numbers default alignment is Right Alignment(>)
………………………………………………………………………………………………
Eg-3:
Print Decimal value in binary, octal and hexadecimal form
print("Binary Form:{0:b}".format(153))
print("Octal Form:{0:o}".format(153))
print("Hexa decimal Form:{0:x}".format(154))
print("Hexa decimal Form:{0:X}".format(154))
Output:
Binary Form:10011001
Octal Form:231
Hexa decimal Form:9a
Hexa decimal Form:9A
Note:
We can represent only int values in binary, octal and
hexadecimal and it is not possible for float values.
…………………………………………………………………………………..
Note:
{:5d} It takes an integer argument and assigns a minimum
width of 5. {:8.3f} It takes a float argument and assigns a
minimum width of 8 including "." and after decimal point
excatly 3 digits are allowed with round operation if required
{:05d} The blank places can be filled with 0. In this place only
0 allowed.
………………………………………………………………………………………..
Case-3: Number formatting for signed numbers