Thursday, December 26, 2019

String data type


The most commonly used object in any project and in any programming language is String only. Hence we should aware complete information about string data type.

What is string ?
Any sequence of characters within either single quotes or double quotes is considered as a string.

Syntax:

s = ‘karthik’
s = “karthik”

Note: In most of other languages like C, C++, Java a single character with in single quotes is treated as char data type value. But in python we are not having char datatype. Hence it is treated as String only.

Eg: 

>>> ch = ‘a’
>>> type(ch)
<class ’str’>

How to define multi-line string literals ?
We can define multi-line string literals by using triple single or double quotes 

Eg:
>>> s = ‘’’karthik
testing
solutions’'' 

We can also use triple quotes to use single quotes or double quotes as symbol  inside string literal

s = ’This is ’single quote symbol’ —> invalid
s = ’This is \’ single quote symbol’ —> valid 
s = “This is ’single quote symbol” —> valid 
s = ’This is “ double quotes symbol’ —> valid 
s = ’The “Python Notes” by ‘karthik’ is very helpful’ —> invalid 
s = “The “Python Notes” by ‘karthik’ is very helpful” —> invalid 
s = ’The \”Python Notes\” by \’karthik\’ is very helpful’ —> valid 
s = ‘’’The  “Python Notes” by ‘durga’ is very helpful’’’ —> valid 

How to Access characters of a string ?

We can access characters of a string by using the following ways.
By using index 
By using slice operator 

Accessing characters by using index:

Python supports both +ve and -ve index 

+ve index means left to right ( forward direction )
-ve index means right to left ( backward direction )

Eg:  s = ‘karthik’

>>> s=‘karth’
>>> s[0]
‘k’
>>> s[4]
h’
>>> s[-1]
‘h’
>>> s[10]
indexError: string index out of range 

Note: if we are trying to access characters of a string with out of range index then we will get error saying: IndexError

Write a program to accept some string from the keyboard and display its characters by index wise ( both positive and negative index) 

test.py

s=input(“Enter some string:”)
i=0
for x in s:
print(“The character present at positive index {} and at negative index {} is {}” .format(I,i-len(s),x))
i=i+1

Output: 
D:\python_classes>py test.py

Enter Some String:karth

The character present at positive index 0 and at negative index -5 is k
The character present at positive index 1 and at negative index -4 is a
The character present at positive index 2 and at negative index -3 is r
The character present at positive index 3 and at negative index -2 is t
The character present at positive index 4 and at negative index -1 is h

Accessing characters by using slice operator: 

Syntax: s[bEginindex:endindex:step]

Begin Index: From where we have to consider slice (substring)
End Index: we have to terminate the slice (substring) at endindex-1
Step: Incremented Value

Note: 

If we are not specifying bEgin index then it will consider from bEginning of the string.
If we are not specifying end index then it will consider up to end of the string.
The default value for step is 1 

>>> s=“Learning Python is very very easy!!!”
>>> s[1:7:1]
‘earnin’
>>> s[1:7]
‘earnin’
>>> s[1:7:2]
‘eri’
>>> s[:7]
‘Learnin’
>>> s[7:]
‘g Python is very very easy!!!’
>>> s[::]
‘Learning Python is very very easy!!!’
>>> s[:]
‘Learning Python is very very easy!!!’
>>> s[::-1]
‘!!!ysae yrev yrev si nohtyp gninraeL’

Behavior of slice operator:

s[bEgin:end:step]
Step value can be either +ve or -ve 
If +ve then it should be forward direction(left to right) and we have to consider bEgin to end -1 
If -ve then it should be backward direction(right to left) and we have to consider bEgin to end +1 

Note:

In the backward direction if end value is -1 then result is always empty.
In the forward direction if end value is 0 then result is always empty.

In forward direction:

default value for bEgin: 0
default value for end: length of string
default value for step: +1 

In Backward Direction :

default value for bEgin: -1 
default value for end: -(length of string+1)

Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin and end index.

Slice operator case study  

S = ‘abcdefghij’
s[1:6:2]  —> ‘bdf’
s[::1] —>  ‘abcdefghij’
s[::-1] —> ‘jihgfedcba’
S[3:7:-1] —> ‘'
s[7:4:-1] —> ‘hgf’
s[0:10000:1] —> ‘abcdefghij’
s[-4:1:-1] —> ‘gfedc’
s[-4:1:-2] —> ‘gec’
s[5:0:1] —> ‘'
s[9:0:0] —> ValueError: slice step cannot be zero 
s[0:-10:-1]  —> ‘'
s[0:-11:-1] —> ‘a’
s[0:0:1] —> ‘'
s[0:-9:-2] —> ‘'
s[-5:-9:-2] —> ‘fd’
s[10:-1:-1] —> ‘'
s[10000:2:-1] —> ‘jihgfed’

Note: Slice operator never raises IndexError

Mathematical operations for string:

We can apply the following mathematical operators for strings.

Operators for concatenation 
Operators for repetition 

print(“karth”+”ik”) —> karthik 
print(“karthik”*2) —> karthikkarthik 

Note:
To use + operator for strings, compulsory both arguments should be str type.
To use * operator for strings , compulsory one argument should be str and other argument should be int

len() in-built function 

We can use len() function to find the number of characters present in the string.

Eg: 

s = ‘kaushik’
print(len(s))  —> 5 

Write a program to access each character of sting in forward and backward direction using while loop ?

s = “Learning Python is very easy!!!”
n = len(s) 
i = 0
print(“Forward direction”)
while I<n:
print(s[I], end=‘ ‘)
i +=1
print(“Backward direction”)
i = -1
while i >=-n:
print(s[I],end=‘ ‘)
i = i-1
  
Alternative ways 

s = “Learning Python is very easy !!!”
print(“Forward direction”)
for i in s:
print(I,end=‘ ‘)
print(“Forward direction”)
for I in s[::]:
print(I,end=‘ ‘)

print(“Backward direction”)
for I in s[::-1]:
print(I,end=‘ ‘)

Checking Membership:

We can check whether the character or string is the member of another string or not by using in and not in operators

s = ‘karth’
print(‘k’ in s) —> True 
print(‘2’ in s) —> False 

s = input(“Enter main string:”)
subs = input(“Enter sub string:”)
if subs in s:
   print(subs, “is found in main string”)
else:
   print(subs, “is not found in main string”)

Output:

D:\Python_classes>py test.py 
Enter main string: karthsoftwaresolutions 
Enter sub string:karth
karth is found in main string

D:\Python_classes>py test.py 
Enter main string: karthsoftwaresolutions 
Enter sub string:python
karth is not found in main string

Comparison of strings:

We can use comparison operators  (<,<=,>,>=)  and equality operators  (==, !=) for strings.
Comparison will be performed based on alphabetical order 

s1=input(“Enter first string:”)
s2=input(“Enter Second string:”)
if s1==s2:
print(“Both strings are equal”)
elif s1<s2:
print(“First String is less than Second String”)
else:
print(“First String is greater than Second String”)

Output:

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:karth
Both strings are equal 

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:ravi
Both strings is less than Second String

D:\Python_classes>py test.py 
Enter first string:karth
Enter Second string:anil
Both strings is greater than Second String

Removing Spaces from the string:

We can use the following 3 methods 

rstrip()  —> To remove spaces at right hand side 
lstrip() —> To remove spaces at left hand side
strip() —> To remove spaces both sides 

city=input(“Enter your city Name:”)
scity=city.strip()
If scity==‘Hyderabad’:
print(“Hello Hyderabad..Adab”)
elif scity==‘Chennai’:
print(“Hello Madrasi…Vanakkam”)
elif scity==“Bangalore”:
print(“Hello kannadiga..shubhodaya”)
else:
print(“your entered city is invalid”)

Finding Substrings:

We can use the following 4 methods 

For Forward direction:

  1. Find()
  2. index()

For Backward direction:

  1. rfind()
  2. rindex()

find():

s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will get  -1.

s=“learning Python is very easy”
print(s.find(“Python”)) #9
print(s.find(“Java”)) #-1
print(s.find(“r”))#3
print(s.rfind(“r”))#21

Note: By default find() method  can search total string. We can also specify the boundaries to search.

s.find(substring, bEgin,end)
It will always search from bEgin index to end -1 index.

s=“karthravipavanshiva”
print(s.find(‘a’))#4
print(s.find(‘a’,7,15))#10
print(s.find(‘z’,7,15))#-1

index():

Index() method is exactly same as find()  method except that if the specified substring is not available then we will get valueerror

s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
try:
n=s.index(subs)
except  ValueError:
print(“substring not found”)
else:
print(“substring found”)

Output
 
D:\python_classes>py test.py 
Enter main string:learning python is very easy
Enter sub string:python 
substring found 

D:\python_classes>py test.py 
Enter main string:learning python is very easy
Enter sub string:java
Substring not  found 

Program to display all positions of substring in a given main string 

s=input(“Enter main string:”)
subs=input(“Enter sub string:”)
flag=False
pos=-1
n=len(s)
while True:
pos=s.find(subs,pos+1,n)
if pos==-1:
break
print(“Found at position”,pos)
flag=True
If flag==False:
print(“Not Found”)

Output 

D:\python_classes>py test.py
Enter main string:abbabababacdefg
Enter sub string:a
Found at position 0
Found at position 3
Found at position 5
Found at position 7
Found at position 9
Found at position 11

D:\python_classes>py test.py
Enter main string:abbabababacdefg
Enter sub string:bb
Found at position 1 

Counting substring in the given string:

We can find the number of occurrences of substring present in the given string by using count() method 

  1. s.count(substring) —> it will search through out the string 
  2. s.count(substring, bEgin, end) —> it will search from bEgin index to end -1 index.

s=“abcabcabcabcadda”
print(s.count(‘a’))
print(s.count(‘ab’))
print(s.count(‘a’,3,7))

Output 

6
4
2

Replacing a string with another string:

s.replace(old string, newstring)
Inside s, every occurrence of old string will be replaced with new string.

Eg1

s = “Learning Python is very difficult”
s1 = s.replace(“difficult”, “easy”)
print(s1)

Output :  Learning Python is very easy

Eg2: All occurrences will be replaced

s = “abababaabaaba”
s1 = s.replace(“a”, “b”)
print(s1)

Output : bbbbbbbbbbbbbb

String objects are immutable then how we can change the content by using replace() method 

Once we creates string object, we cannot change the content. This non-changeable behavior is nothing but immutability. If we are trying to change the content by using any method, then with those changes a new object will be created and changes won’t be happened in existing object.

Hence the replace() method also a new object got created but existing object won’t be changed.

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 separator by using split() method.

l=s.split(separator)

The default separator is space, the return type of split() method is list.

s=“karth software solutions”
l=s.split()
for x in l:
print(x)

Output:

karth
software
solutions

s=“22-02-2018”
l=s.split(‘-‘)
for x in l:
print(x)

Output 

22
02
2018

Joining of strings:

We can join a group of strings ( list or tuple ) wrt the given separator 

s = (’sunny’,bunny’,’chinny’)
s = ‘-‘.join(t)
print(s)

Output: sunny-bunny-chinny

Eg-2:

l = [‘hyderabad’,’singapore’,’london’,’dubai’]
s = ‘:’.join(l)
print(s)

Output : hyderabad:singapore:london:dubai

Changing case of string:

 We can change case of a string by using the following 4 methods.

upper() —> to convert all characters to upper case 
lower() —> to convert all characters to lower case 
swapcase —> converts all lower case characters to upper case and all upper case characters to Lower case.
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.
capitaize()  —> only first character will be converted to upper case and all remaining characters can be converted to Lower case

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 east 
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.startwith(substring)
  2. s.endswith(substring)

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.

isalnum(): Returns True if all characters are alphanumeric( a to z, A to Z, 0 to 9)
isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)
isdigit(): Returns True if all characters are digits only( 0 to 9)
islower(): Returns True if all characters are lower case alphabet symbols
Isupper(): Returns True if all characters are upper case alphabet symbols
istitle(): Returns True if string is in title case.
isspace(): Returns True if string contains inly spaces 

Eg:

print(‘Karth786’.isalnum()) —> True
print(‘Karth786’.isalpha()) —> False
print(‘Karth’.isalpha()) —> True
print(‘Karth’.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

Program 

s=input(“Enter any character:”)
if s.isalnum():
print(“Alpha Numeric Character”)
if s.isalpha():
print(“Alphabet character”)
if s.islower():
print(“Lower case alphabet character”)
else:
print(“Upper case alphabet character”)
else:
print(“it is a digit”)
elif s.isspace():
print(“it is space character”)
else:
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 
Lower case alphabet character 

Formatting the Strings:

We can format the strings with variable values by using replacement operator {} and format() method 

name = ‘karth’
salary = 10000
age  = 48 
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 

karth ’s  salary is 10000 and his age is 48 
karth ’s  salary is 10000 and his age is 48 
karth ’s  salary is 10000 and his age is 48 

Important Programs regarding String Concept 

Q1 write a program to reverse the given string 

Input: karth
Output: htrak

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)

Q2 Program to reverse order of words 

Input: Learning Python is vert Easy
Output: Easy Very is Python Learning 

s = input(“Enter Some String:”)
l=s.split()
l1=[]
i=len(l)-1
while i>=0:
l1.append(l[I])
i=I-1
output=‘ ‘.join(l1)
print(output)

Output: Enter Some String:Learning Python is very easy!!
             easy!!! Very is Python Learning 

Program to reverse internal content of each word 

Input: Karth Software Solutions
Output: htrak erawtfos snoituloS

s = input(“Enter Some String:”)
l=s.split()
l1=[]
i=0
while i<len(l):
l1.append(l[I][::-1])
i=i+1
output=‘ ‘.join(l1)
print(output)

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

2nd way:

s=input(“Enter Some String:”)
i=0
print(“Characters at Even Position:”)
while I<len(s):
print(s[I],end=‘,’)
i=i+2 
print()
print(“Characters at Odd Position:”)
i=1
while I<len(s):
print(s[I],end=‘,’)
i=I+2

Program to Merge Characters of 2 Strings into a Single String by talking Characters alternatively 

Input: s1 = “ravi”
          s2 = “reja”

Output: rtaevjia

s1=input(“Enter First String:”)
s2=input(“Enter Second String:”)
output=‘'
i,j=0,0
while I<len(s1) or j<len(s2)
if i<len(s1):
output=output+s1[I]
i+=1
if j<len(s2):
output=output+s2[j]
j+=1
print(output)

Output:

Enter First String:karth
Enter Second String:ravisoft
kraarvgiasoft

Write a program to sort the characters of the string and first alphabet symbols followed by numeric values 

Input: B4A1D3 
Output: ABD134 

s=input(“Enter Some String:”)
s1=s2=output=‘'
for x in s:
If x.isalpha():
s1=s1+x
else:
s2=s2+x
for x in sorted(s1):
output=output+x
for x in sorted(s2):
output=output+x
print(output)

Write a program for the following requirement 

Input: a4b3c2 
Output: aaaabbbcc

s=input(“Enter Some String:”)
output=‘'
for x in s:
if x.isalpha():
output=output+x
previous=x
else:
output=output+previous*(int(x)-1)
print(output)

Note:
chr(unicode) —> The corresponding character 
ord(character) —> The corresponding unicode value

Write a program to perform the following activity 

Input: a4k3b2 
Output: aeknbd

s=input(“Enter Some String”)
output=‘'
for x in s:
If x.isalpha():
output=output+x
previous=x
else:
output=output+chr(ord(previous)+int(x)
print(output)

Write a program to remove duplicate characters from the given input string ?

Input: ABCDABBCDABBBCCCDDEEEF
Ouput: ABCDEF 

s = input(“Enter Some String:”)
l=[]
for x in s:
If x not in l:
l.append(x)
output=“.join(l)
print(output)

Write a program to find the number of occurrences of each character present in the given string ?

s=input(“Enter the Some String:”)
d={}
for x in s:
If x in d.keys():
d[x]=d[x]+1
else:
d[x]=1
for k,v in d.items():
print(“{} = {} Times”.format(k,v))

Write a program to perform the following task ?

Input: 'one two three four five six seven’
Output: ‘one owt three ruof five xis seven’

s = input(‘Enter Some String:’)
l = s.split()
l1 = []
i = 0
while I<len(l):
if I%2==0:
l1.append(l[I])
else
l1.append(l[I][::-1])
i=I+1
output=‘ ‘.join(l1)
print(‘Original String:’,s)
print(‘output String:’,output)

Output:

D:\python_classes>py test.py 
Enter Some String: one two three four five six seven 
Original String: one two three four five six seven 
output String: one owt three ruof five xis seven

Formatting the strings:

We can format the strings with variable values try using replacement operator {} and format () method 
The main objective of format() method to format string into meaningful output form.

Case 1 : Basic formatting for default, positional and keyword arguments 

name = ‘karth’
salary = 10000
age = 48 
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

karth ’s salary is 10000 and his age is 48 
karth ’s salary is 10000 and his age is 48 
karth ’s salary is 10000 and his age is 48 

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: 

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: {:8.3f}”.format(123.45))
print(“The float number is: {:8.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 integrated; 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.
{:5d} it takes 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 exactly 3 digits are allowed with round operation if required.
{:05d} The blank places can be filled with 0. In this place only 0 allowed 

Case3 : Number formatting for signed numbers

> while displaying positive numbers, If we want to include + then we have to write  {:+d} and {:+f}
> using plus for -ve numbers there is no use and for -ve numbers - sign will come automatically.

print(“int value with sign:{:+d}”.format(123))
print(“int value with sign:{:+d}”.format(-123))
print(“int value with sign:{:+f}”.format(123.456))
print(“int value with sign:{:+f}”.format(-123.456))

Output:

int value with sign:+123 
int value with sign:-123 
float value with sign:+123.456000
float value with sign:-123.456000

Case-4 : Number formatting with alignment 

<,>, ^ and = are used for alignment
<  —> left alignment to the remaining space
^  —> center alignment to the remaining space
> —> right alignment to the remaining space
= —> forces the signed (+) (-) to the left most position 

Note: default  alignment for numbers is right alignment.

Eg: 

print(“{:5d}”.format(12))
print(“{:<5d}”.format(12))
print(“{:<05d}”.format(12))
print(“{:>5d}”.format(12))
print(“{:>05d}”.format(12))
print(“{:^5d}”.format(12))
print(“{:=5d}”.format(12))
print(“{:^10.3f}”.format(12.23456))
print(“{:=8.3f}”.format(-12.23456))

Output 

12
12
12000
12
00012
12
-12
12.235
-12.235

Case-5: string formatting with format()
Similar to numbers, we can format string values also with format() method 

s.format(string)

print(“{:5d}”.format(12))
print(“{:5}”.format(“rat”))
print(“{:>5}”.format(“rat”))
print(“{:<5}”.format(“rat”))
print(“{:^5}”.format(“rat”))
print(“{:*^5}”.format(“rat”)) # instead of * we can use any character(like +,$,a etc)

Output 

12
rat
rat
rat
rat
*rat*

Note: for numbers default alignment is right where as for strings default alignment is left 

Case-6 : Truncating strings with format() method 

print(“{:.3}”.format(“karthsoftware”))
print(“{:5.3}”.format(“karthsoftware”))
print(“{:>5.3}”.format(“karthsoftware”))
print(“{:^5.3}”.format(“karthsoftware”))
print(“{:*^5.3}”.format(“karthsoftware”))

Output

kar
kar
kar
kar
*kar*

Case-7 : formatting dictionary members using format()

person={‘age’:48,’name’:’karth’}
print(“{name}’s age is: {age}”.format(**person))

Output: karth’s  age is:48 

Case-8 : formatting class members using format() 

class Person:
age=48
name=“kashu”
print(“{p.name}’s age is :{p.age}”.format(p=Person()))

Output : karth’s age is :48 

class Person:
def_init_(self, name,age):
self.name=name
self.age=age
print(“{p.name}’s age is :{p.age}”.format(p=Person(‘karth’,48)))
print(“{p.name}’s age is :{p.age}”.format(p=Person(‘Ravi’,48)))

Note: Here person object is passed as keyword argument. We can access by using its reference variable in the template string.

 Class-9:  Dynamic formatting using format() 

string=“{:{fill}{align}{width}}”
print{string.format(‘cat’,fill=‘*’,align=‘^’,width=5))
print(string.format(‘cat’,fill=‘*’,align=‘^’,width=6))
print(string.format(‘cat’,fill=‘*’,align=‘<’,width=6))
print(string.format(‘cat’,fill=‘*’,align=‘>’,width=6))

Output:

*cat*
*cat**
cat***
***cat

Class-10: Dynamic float format template

num=“{:{align}{width}.{precision}f}”
print(num.format(123.236,align=‘<‘,width=8,precision=2))
print(num.format(123.236,align=‘>‘,width=8,precision=2))

Output:

123.24
123.24

Case-11: formatting date values 

import datetime
#datetime formatting 
date=datetime.datetime.now()
print(“it’s now:{:%d/%m/%Y  %H:%M:%S}”.format(date))

Output: it’s now: 09/03/2018 12:36:26

Case-12: Formatting complex numbers 

complexNumbers=1+2j
print(“Real Part:{0.real} and Imaginary Part:{0.imag}”.format(complexNumber))


Output: Real Part: 1.0 and Imaginary Part: 2.0 





1 comment:

  1. Kaushik Gattu: String Data Type >>>>> Download Now

    >>>>> Download Full

    Kaushik Gattu: String Data Type >>>>> Download LINK

    >>>>> Download Now

    Kaushik Gattu: String Data Type >>>>> Download Full

    >>>>> Download LINK iq

    ReplyDelete