String
In python str class is a predefined class used to represent sequence of character or string. To create the
object of str class the syntax is,
str(object='') -> str
Also we can create a string object using single quote or double quote or triple single quote or triple
double quote.
Let’s go for an example, how to create the object str class,
obj = str ()
print ( obj , type ( obj ))
obj = str ( "lit" )
print ( obj , type ( obj ))
obj = "india"
print ( obj , type ( obj ))
obj = 'litindia'
print ( obj , type ( obj ))
obj = """this is
a multi line
string """
print ( obj , type ( obj ))
obj = '''india
is the
best '''
print ( obj , type ( obj ))
[litindia@localhost demo]$ python [Link]
<class 'str'>
lit <class 'str'>
india <class 'str'>
litindia <class 'str'>
this is
a multi line
string <class 'str'>
india
is the
best <class 'str'>
From the above program we can identify that, the difference between single quote and triple quote is,
single quote used for one line string and triple quote used for multiline string.
In C, C++, Java a single character with single quoted is treated as char data type. But python does not
supports char data type. In python char is also represented as a string object.
var = 'a'
print ( var , type ( var ))
[litindia@localhost demo]$ python [Link]
a <class 'str'>
We can find the length of a string using len() function. Let’s go for an example how to use len() function
with string object,
obj1 = "india"
print ( obj1 , len ( obj1 ))
obj2 = 'lit india'
print ( obj2 , len ( obj2 ))
[litindia@localhost demo]$ python [Link]
india 5
lit india 9
String supports both +ve index and –ve index.
strObject = “INDIA”
I N D I A
0 index 1 index 2 index 3 index 4 index
-5 index -4 index -3 index -2 index -1 index
strObject = "INDIA"
print ( strObject [ 0 ], strObject [ -5 ])
print ( strObject [ 1 ], strObject [ -4 ])
print ( strObject [ 2 ], strObject [ -3 ])
print ( strObject [ 3 ], strObject [ -2 ])
print ( strObject [ 4 ], strObject [ -1 ])
[litindia@localhost demo]$ python [Link]
I I
NN
DD
I I
AA
String is an immutable object in python. In python string object does not supports item assignment. We
can’t modify a string one a string is created.
Let’s go for an example to understand what immutable string is,
strObject = "INDIA"
print ( strObject )
strObject [ 0 ] = 'i' # Error
print ( strObject )
[litindia@localhost demo]$ python [Link]
INDIA
Traceback (most recent call last):
File "[Link]", line 6, in <module>
strObject [ 0 ] = 'i'
TypeError: 'str' object does not support item assignment
From the above program we can identify that, if we try to modify a string then it will raise TypeError
exception, because string is immutable object.
String Operators:
1. arithmetic +, *, %
2. relational ==, >=, >, <, <=, !=
3. membership in, not in
4. slicing [ start index : stop index : step index ]
Arithmetic operator with string:
We can use arithmetic operator with string object. Let’s go for an example, how to user arithmetic
operators with string objects,
strObject = 'Hello ' + 'Sir' # string concatenation
print ( strObject )
strObject = 'Hi ' * 3 # string repetition
print ( strObject )
strObject = 'Hello %s your age is %d' # string formatting
print ( strObject )
print ( strObject % ( 'Raja', 21 ))
print ( strObject % ( 'Rani', 18 ))
[litindia@localhost demo]$ python [Link]
Hello Sir
Hi Hi Hi
Hello %s your age is %d
Hello Raja your age is 21
Hello Rani your age is 18
From the above program we can identify that, + operator is used to perform string concatenation, *
operator is used for string repetition and % operator is used for string formatting.
In python we can’t use + operator between string and integer object.
strObject = 'Value is : ' + 10
print ( strObject )
[litindia@localhost demo]$ python [Link]
Traceback (most recent call last):
File "[Link]", line 3, in <module>
strObject = 'Value is : ' + 10
TypeError: Can't convert 'int' object to str imp
From the above program we can identify that, if we try to use + operator between string and integer
object it will raise TypeError exception.
Relational operator with string:
We can use relational operator with string object in python. Comparison will be performed based on
alphabetical order.
Let’s go for an example how to user relational operator with string object,
print ( 'A' < 'B' )
print ( 'A' > 'B' )
print ( 'A' == 'B' )
print ( 'A' != 'B' )
[litindia@localhost demo]$ python [Link]
True
False
False
True
Membership operator with string:
We can implement membership operator ( in, not in ) with string object. Membership operator only
returns True or False based on sub string found or not.
strObject = 'hello sir i am litindia'
print ( strObject )
subStr = input ( 'Enter string : ')
print ( subStr in strObject )
[litindia@localhost demo]$ python [Link]
hello sir i am litindia
Enter string : hello
True
[litindia@localhost demo]$ python [Link]
hello sir i am litindia
Enter string : sir
True
[litindia@localhost demo]$ python [Link]
hello sir i am litindia
Enter string : india
True
[litindia@localhost demo]$ python [Link]
hello sir i am litindia
Enter string : bye
False
Slicing operator with string:
To use slicing operator with string object, there are two different ways are available.
strObject [ start index : stop index ]
strObject [ start index : stop index : step index ]
If we are not specifying start index then it will consider from beginning of the string.
If we are not specifying stop index then it will consider up to end of the string. The default value for step
is 1.
Step value can be +ve value or –ve value. If step value is +ve, that indicate forward traversing. If step
value –ve that indicate backward traversing. The default start is 0 index and stop is length of string if that
is forward traversing. The default start is -1 and stop is –( length of string + 1 ) if that is backward
traversing.
Let’s go for an example, how to user slicing operator with string object,
strObject = 'Hello Sir'
print ( strObject )
print ( strObject [ : ] ) # default start 0 default stop len ( strObject )
print ( strObject [ 0 : 5 ]) # default step is +1
print ( strObject [ 6 : ]) # default stop len ( strObject )
print ( strObject [ 0 : 5 : 2 ])
print ( strObject [ : : -1 ]) # default start -a deffault stop - ( len ( strObject) + 1 )
[litindia@localhost demo]$ python [Link]
Hello Sir
Hello Sir
Hello
Sir
Hlo
riS olleH
String Methods:
Slno method name Return Task
Type
1 [Link]() str Return a capitalized version of S, i.e.
make the first character have upper
case and the rest lower case.
2 [Link]() str Return a version of S suitable for
caseless comparisons.
3 [Link](width[, str Return S centered in a string of
fillchar]) length width. Padding is done using
the specified fill character (default is
a space)
4 [Link](sub[, start[, int Return the number of non-
end]]) overlapping occurrences of substring
sub in string S[start:end]. Optional
arguments start and end are
interpreted as in slice notation.
5 [Link](encoding='utf- bytes Encode S using the codec registered
8', errors='strict') for encoding. Default encoding is
'utf-8'. errors may be given to set a
different error handling scheme.
Default is 'strict' meaning that
encoding errors raise a
UnicodeEncodeError. Other possible
values are 'ignore', 'replace' and
'xmlcharrefreplace' as well as any
other name registered with
codecs.register_error that can handle
UnicodeEncodeErrors.
6 [Link](suffix[, bool Return True if S ends with the
start[, end]]) specified suffix, False otherwise.
With optional start, test S beginning
at that position. With optional end,
stop comparing S at that position.
suffix can also be a tuple of strings to
try.
7 [Link](tabsize=8) str Return a copy of S where all tab
characters are expanded using
spaces. If tabsize is not given, a tab
size of 8 characters is assumed.
8 [Link](sub[, start[, end]]) int Return the lowest index in S where
substring sub is found, such that sub
is contained within S[start:end].
Optional arguments start and end
are interpreted as in slice notation.
Return -1 on failure.
9 [Link](*args, str Return a formatted version of S,
**kwargs) using substitutions from args and
kwargs.
The substitutions are identified by
braces ('{' and '}').
10 S.format_map(mapping) str Return a formatted version of S,
using substitutions from mapping.
The substitutions are identified by
braces ('{' and '}').
11 [Link](sub[, start[, int Like [Link]() but raise ValueError
end]]) when the substring is not found.
12 [Link]() bool Return True if all characters in S are
alphanumeric and there is at least
one character in S, False otherwise.
13 [Link]() -> bool Return True if all characters in S are
| alphabetic and there is at least one
| character in S, False otherwise.
14 [Link]() -> bool Return True if there are only decimal
characters in S, False otherwise.
15 [Link]() -> bool Return True if all characters in S are
digits and there is at least one
character in S, False otherwise.
16 [Link]() bool Return True if S is a valid identifier
according to the language definition.
Use keyword. iskeyword() to test for
reserved identifiers such as "def" and
"class".
17 [Link]() bool Return True if all cased characters in
S are lowercase and there is at least
one cased character in S, False
otherwise.
18 [Link]() bool Return True if there are only numeric
characters in S, False otherwise.
19 [Link]() bool Return True if all characters in S are
considered printable in repr() or S is
empty, False otherwise.
20 [Link]() bool Return True if all characters in S are
whitespace and there is at least one
character in S, False otherwise.
21 [Link]() bool Return True if S is a titlecased string
and there is at least one character in
S, i.e. upper- and titlecase characters
may only follow uncased characters
and lowercase characters only cased
ones. Return False otherwise.
22 [Link]() bool Return True if all cased characters in
S are uppercase and there is at least
one cased character in S, False
otherwise.
23 [Link](iterable) str Return a string which is the
concatenation of the strings in the
iterable. The separator between
elements is S.
24 [Link](width[, fillchar]) str Return S left-justified in a Unicode
string of length width. Padding is
done using the specified fill character
(default is a space).
25 [Link]() str Return a copy of the string S
converted to lowercase.
26 [Link]([chars]) str Return a copy of the string S with
leading whitespace removed. If chars
is given and not None, remove
characters in chars instead.
27 [Link](sep) (head, sep, Search for the separator sep in S, and
tail) return the part before it, the
separator itself, and the part after it.
If the separator is not found, return S
and two empty strings.
28 [Link](old, new[, str Return a copy of S with all
count]) occurrences of substring old replaced
by new. If the optional argument
count is given, only the first count
occurrences are replaced.
29 [Link](sub[, start[, int Return the highest index in S where
end]]) substring sub is found, such that sub
is contained within S[start:end].
Optional arguments start and end
are interpreted as in slice notation.
Return -1 on failure.
30 [Link](sub[, start[, int Like [Link]() but raise ValueError
end]]) when the substring is not found.
31 [Link](width[, fillchar]) str Return S right-justified in a string of
length width. Padding is done using
the specified fill character (default is
a space).
32 [Link](sep) (head, sep, Search for the separator sep in S,
tail) starting at the end of S, and return
the part before it, the separator itself,
and the part after it. If the separator
is not found, return two empty
strings and S.
33 [Link](sep=None, list of Return a list of the words in S, using
maxsplit=-1) strings sep as the delimiter string, starting at
the end of the string and working to
the front. If maxsplit is given, at
most maxsplit splits are done. If sep
is not specified, any whitespace
string is a separator.
34 [Link]([chars]) str Return a copy of the string S with
trailing whitespace removed.
If chars is given and not None,
remove characters in chars instead.
35 [Link](sep=None, list of Return a list of the words in S, using
maxsplit=-1) strings sep as the delimiter string. If
maxsplit is given, at most maxsplit
splits are done. If sep is not specified
or is None, any whitespace string is a
separator and empty strings are
removed from the result.
36 [Link]([keepends]) list of Return a list of the lines in S,
strings breaking at line boundaries.
Line breaks are not included in the
resulting list unless keepends is
given and true.
37 [Link](prefix[, bool Return True if S starts with the
start[, end]]) specified prefix, False otherwise.
With optional start, test S beginning
at that position.
With optional end, stop comparing S
at that position. prefix can also be a
tuple of strings to try.
38 [Link]([chars]) str Return a copy of the string S with
leading and trailing whitespace
removed. If chars is given and not
None, remove characters in chars
instead.
39 [Link]() str Return a copy of S with uppercase
characters converted to lowercase
and vice versa.
40 [Link]() str Return a titlecased version of S, i.e.
words start with title case characters,
all remaining cased characters have
lower case.
41 [Link](table) str Return a copy of the string S in
which each character has been
mapped through the given
translation table. The table must
implement lookup/indexing via
__getitem__, for instance a dictionary
or list, mapping Unicode ordinals to
Unicode ordinals, strings, or None. If
this operation raises LookupError,
the character is left untouched.
Characters mapped to None are
deleted.
42 [Link]() str Return a copy of S converted to
uppercase.
43 [Link](width) str Pad a numeric string S with zeros on
the left, to fill a field of the specified
width. The string S is never
truncated.
String case method:
We can change the case of a string using by using following 6 method,
1. upper ()
2. lower ()
3. swapcase ()
4. title ()
5. capitalize ()
6. casefold ()
[Link]() method return a copy of S converted to uppercase.
[Link]() method return a copy of the string S converted to lowercase.
[Link]() method return a copy of S with uppercase characters converted to lowercase and vice versa.
[Link]() method return a titlecased version of S, i.e. words start with title case characters, all remaining
cased characters have lower case.
[Link] () method return a capitalized version of S, i.e. make the first character have upper case and
the rest lower case.
[Link]() method return a version of S suitable for caseless comparisons.
Let’s go for an example how to use these methods with string object,
strObject = 'welcome to INDIA'
print ( 'Origional : ', strObject )
print ( 'Upper : ', strObject . upper () )
print ( 'Lower : ', strObject . lower () )
print ( 'Swapcase : ',strObject . swapcase () )
print ( 'Title : ', strObject . title () )
print ( 'Capitalize : ', strObject . capitalize () )
print ( 'Casefold : ', strObject . casefold () )
[litindia@localhost demo]$ python [Link]
Origional : welcome to INDIA
Upper : WELCOME TO INDIA
Lower : welcome to india
Swapcase : WELCOME TO india
Title : Welcome To India
Capitalize : Welcome to india
Casefold : welcome to india
String type method:
To check the type of the string we can use bellow 11 types of methods.
1. isalnum()
2. isalpha()
3. isdecimal()
4. isdigit()
5. isnumeric()
6. isidentifier()
7. islower ()
8. isupper ()
9. istitile ()
10. isspace ()
11. isprintable()
Let’s go for an example how to use these methods with string object,
strObject = 'litindia123'
print ( strObject, 'Is a alphanumeric string : ', strObject . isalnum () )
strObject = 'litindia'
print ( strObject, 'Is a alphabetic string : ', strObject . isalpha () )
strObject = '123'
print ( strObject, 'Is a numerical string : ', strObject . isdigit () )
strObject = 'litindia'
print ( strObject, 'Is a lower case string : ', strObject . islower () )
strObject = 'LITINDIA'
print ( strObject, 'Is a upper case string : ', strObject . isupper () )
strObject = 'Lit India'
print ( strObject, 'Is a title string : ', strObject . istitle () )
strObject = ' '
print ( strObject, 'Is a space string : ', strObject . isspace () )
[litindia@localhost demo]$ python [Link]
litindia123 Is a alphanumeric string : True
litindia Is a alphabetic string : True
123 Is a numerical string : True
litindia Is a lower case string : True
LITINDIA Is a upper case string : True
Lit India Is a title string : True
Is a space string : True
Count method:
To count the number of occurrence of a sub string in a string object, we can use count method.
[Link](sub[, start[, end]])
Count method return the number of non-overlapping occurrences of substring sub in string S[start:end].
Optional arguments start and end are interpreted as in slice notation.
Let’s go for an example how to use count method with string object,
strObject = 'Hello sir i am lit, welcome to litindia'
print ( strObject )
subStr = input ( 'Enter sub string to count the number of occurrence : ')
print ( strObject . count ( subStr ) )
[litindia@localhost demo]$ python [Link]
Hello sir i am lit, welcome to litindia
Enter sub string to count the number of occurrence : sir
1
[litindia@localhost demo]$ python [Link]
Hello sir i am lit, welcome to litindia
Enter sub string to count the number of occurrence : lit
2
Find and Index method:
To get the index position of a sub string in a string object, we can use the bellow methods.
1. find ()
2. rfind ()
3. index ()
4. rindex ()
Find and index method search sub string from forward direction, and rfind and rindex method search
sub string from reverse direction.
[Link](sub[, start[, end]])
Find method return the lowest index in S where substring sub is found, such that sub is contained within
S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.
[Link](sub[, start[, end]])
Index method is like [Link]() but raise ValueError when the substring is not found.
[Link](sub[, start[, end]])
Rfind method return the highest index in S where substring sub is found, such that sub is contained
within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on
failure.
[Link](sub[, start[, end]])
Rindex method is like [Link]() but raise ValueError when the substring is not found.
Let’s go for an example to understand how to work with find, index, rfind and rindex method,
strObject = 'india'
print ( strObject . find ( 'i' ))
print ( strObject . index ( 'i' ))
print ( strObject . rfind ( 'i' ))
print ( strObject . rindex ( 'i' ))
print ( strObject . find ( 'z' ))
print ( strObject . index ( 'z' ))
[litindia@localhost demo]$ python [Link]
0
0
3
3
-1
Traceback (most recent call last):
File "[Link]", line 12, in <module>
print ( strObject . index ( 'z' ))
ValueError: substring not found
From the above program we can identify that, the major difference between find and index method is, on
failure find method returns -1 but on failure index method raise ValueError exception.
Split method:
To split a string using a separator in python we can use 3 different methods given below.
1. split ()
2. rsplit ()
3. splitlines ()
[Link](sep=None, maxsplit=-1)
Split method returns a list of the words in S, using sep as the delimiter string. If maxsplit is given, at
most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and
empty strings are removed from the result.
[Link](sep=None, maxsplit=-1)
Rsplit method returns a list of the words in S, using sep as the delimiter string, starting at the end of the
string and working to the front. If maxsplit is given, at most maxsplit splits are done. If sep is not
specified, any whitespace string is a separator
[Link]([keepends])
Splitlines method returns a list of the lines in S, breaking at line boundaries.
Let’s go for an example how to use split, rsplit and splitlines method with string object,
strObject = 'Welcome to lit'
print ( strObject . split () )
strObject = "12-10-2020"
print ( strObject . split ( '-' ))
print ( strObject . split ( '-', 1 ))
print ( strObject . rsplit ( '-', 1 ))
strObject = '''hello sir
welcome to
lit india'''
print ( strObject . splitlines () )
[litindia@localhost demo]$ python [Link]
['Welcome', 'to', 'lit']
['12', '10', '2020']
['12', '10-2020']
['12-10', '2020']
['hello sir', 'welcome to ', 'lit india']
From the above program we can identify that, how to work with split method, rspit method and
splielines method.
Partition method:
For partition of a string object using a separator we can use bellow 2 methods,
1. partition()
2. rpartition ()
[Link](sep)
Partition method search for the separator sep in S, and return the part before it, the separator itself, and
the part after it. If the separator is not found, return S and two empty strings.
[Link](sep)
Rpartition method search for the separator sep in S, starting at the end of S, and return the part before it,
the separator itself, and the part after it. If the separator is not found, return two empty strings and S.
Let’s go for an example how to implement partition and rpartition method with string object,
strObject = "hi Lit Hello Lit Bye"
print ( strObject . partition ( 'Lit' ))
print ( strObject . rpartition ( 'Lit' ))
[litindia@localhost demo]$ python [Link]
('hi ', 'Lit', ' Hello Lit Bye')
('hi Lit Hello ', 'Lit', ' Bye')
Join method:
To join the strings present in an iterable object using a separator we can use bellow method.
1. join ()
[Link](iterable)
Join method return a string which is the concatenation of the strings in the iterable. The separator
between elements is S.
Let’s go for an example how to use join method using string object,
iterableObject = [ 'a', 'b', 'c', 'd' ]
print ( '-' . join ( iterableObject ))
print ( '$' . join ( iterableObject ))
print ( '*' . join ( iterableObject ))
print ( ' ' . join ( iterableObject )) # by using space
print ( '' . join ( iterableObject )) # by using empty string
[litindia@localhost demo]$ python [Link]
a-b-c-d
a$b$c$d
a*b*c*d
abcd
abcd
Replace method:
To implement replace mechanism in a string object, we can use bellow method.
1. replace ()
[Link](old, new[, count])
Replace method return a copy of S with all occurrences of substring old replaced by new. If the optional
argument count is given, only the first count occurrences are replaced.
Let’s go for an example how to use replace method with string object,
strObject = 'litindia'
print ( strObject )
print ( strObject . replace ( 'i', 'I' )) # count parameter is not given
print ( strObject . replace ( 'i', 'I' , 1 )) # count parameter is given
[litindia@localhost demo]$ python [Link]
litindia
lItIndIa
lItindia
Strip method:
1. strip ()
2. rstrip ()
3. lstrip ()
[Link]([chars])
Strip method return a copy of the string S with leading and trailing whitespace removed. If chars is given
and not None, remove characters in chars instead.
[Link]([chars])
Rstrip method return a copy of the string S with trailing whitespace removed. If chars is given and not
None, remove characters in chars instead.
[Link]([chars])
Lstrip method return a copy of the string S with leading whitespace removed. If chars is given and not
None, remove characters in chars instead.
Let’s go for an example how to use strip method with string object,
strObject = ' LitIndia ' # 3 white space taken before value and after value
print ( strObject , len ( strObject ))
x = strObject . lstrip () # leading white space removed
print ( x, len ( x ))
y = strObject . rstrip () # trailing whit space removed
print ( y, len ( y ))
z = strObject . strip () # leading and trailing white space removed
print ( z , len ( z ))
[litindia@localhost demo]$ python [Link]
LitIndia 14
LitIndia 11
LitIndia 11
LitIndia 8
Justified method:
To justify a string in left, right or in center we can use bellow methods.
1. ljust
2. rjust
3. center
[Link](width[, fillchar])
Rjust method return S right-justified in a string of length width. Padding is done using the specified fill
character (default is a space).
[Link](width[, fillchar])
Ljust method return S left-justified in a Unicode string of length width. Padding is done using the
specified fill character (default is a space).
[Link](width[, fillchar])
Center method return S centered in a string of length width. Padding is done using the specified fill
character (default is a space)
# Person 1
name1 = 'sritam'
age1 = '29'
gender1 = 'Male'
# Person 2
name2 = 'sujit'
age2 = '28'
gender2 = 'Male'
# Person 3
name3 = 'Suchismita'
age3 = '24'
gender3 = 'Female'
print ( 'Name'. center (10), 'Age' . center ( 5 ), 'Gender' . center ( 10 ) )
print ( name1 . ljust ( 10 ), age1 . center ( 5 ), gender1 . rjust ( 10 ) )
print ( name2 . ljust ( 10 ), age2 . center ( 5 ), gender2 . rjust ( 10 ) )
print ( name3 . ljust ( 10 ), age3 . center ( 5 ), gender3 . rjust ( 10 ) )
[litindia@localhost demo]$ python [Link]
Name Age Gender
sritam 29 Male
sujit 28 Male
Suchismita 24 Female
Formatting method
We can format the string with variable value by using below methods.
1. format()
2. formatmap ()
[Link](*args, **kwargs)
Format method return a formatted version of S, using substitutions from args and kwargs. The
substitutions are identified by braces ('{' and '}').
S.format_map(mapping)
Format_map method returns a formatted version of S, using substitutions from mapping. The
substitutions are identified by braces ('{' and '}').
Let’s go for an example how to user formatting method with string object,
print ( "{}'s salary is {} and his age is {}." . format ( 'Suchismita', 1540, 24 ))
print ( "{}'s salary is {:08.2f} and his age is {}." . format ( 'Suchismita', 1540, 24 ))
print ( "{0}'s salary is {1} and his age is {2}." . format ( 'Sritam', 285000, 27 ))
print ( "{0}'s salary is {1:08.2f} and his age is {2}." . format ( 'Sritam', 2850.12645, 27 ))
print ( "{x}'s salary is {y} and his age is {z}." . format ( x='Sujit', y=285000, z=26 ))
print ( "{x}'s salary is {y} and his age is {z}." . format ( x='Sujit', y=285000, z=26 ))
[litindia@localhost demo]$ python [Link]
Suchismita's salary is 1540 and his age is 24.
Suchismita's salary is 01540.00 and his age is 24.
Sritam's salary is 285000 and his age is 27.
Sritam's salary is 02850.13 and his age is 27.
Sujit's salary is 285000 and his age is 26.
Sujit's salary is 285000 and his age is 26.
From the above program we can identify that,
{:08.2f} It takes a float argument and assigns a minimum width of 8 including "." and after decimal point
exactly 2 digits are allowed with round operation if required, the blank places can be filled with 0.
We can implement number formatting with alignment.
< used for left alignment
> used for right alignment
^ used for center alignment
= Forces the signed (+ or -) to the left most position.
print ( '{}' . format ( 12 ))
print ( '{:06d}' . format ( 12 ))
print ( '{:>06d}' . format ( 12 ))
print ( '{:<06d}' . format ( 12 ))
print ( '{:^06d}' . format ( 12 ))
print ( '{:>06d}' . format ( -12 ))
print ( '{:=06d}' . format ( -12 ))
[litindia@localhost demo]$ python [Link]
12
000012
000012
120000
001200
000-12
-00012
From the above program we can identify that, default alignment for number is right alignment.
The format_map(mapping) is similar to [Link](**mapping) method.
Let’s go for an example how to user format_map method with string object,
print ( "{name}'s age is {age} and his salary is {salary}." . format ( name = "raja", age
= 23, salary = 100000))
dict = { 'name' : "raja", 'age' : 23, 'salary' : 100000}
print ( "{name}'s age is {age} and his salary is {salary}." . format ( ** dict ))
print ( "{name}'s age is {age} and his salary is {salary}." . format_map ( dict ))
[litindia@localhost demo]$ python [Link]
raja's age is 23 and his salary is 100000.
raja's age is 23 and his salary is 100000.
raja's age is 23 and his salary is 100000.
Encoding and Decoding method
[Link](encoding='utf-8' )
Encode method encode S using the codec registered for encoding. Default encoding is 'utf-8'. Encode
method convert string object to bytes object. And to convert bytes object to string object we can use
decode method.
Let’s go for an example how to use encode and decode method,
strObject = 'litindia'
enc_strObject = strObject . encode ( 'utf-16' )
dec_strObject = enc_strObject . decode ( 'utf-16' )
print ( strObject )
print ( enc_strObject )
print ( strObject == dec_strObject )
[litindia@localhost demo]$ python [Link]
litindia
b'\xff\xfel\x00i\x00t\x00i\x00n\x00d\x00i\x00a\x00'
True
Zfill method:
To pad a numeric string with zeros we can use bellow method.
[Link](width)
Zfill method pad a numeric string S with zeros on the left, to fill a field of the specified width. The string
S is never truncated.
empId = 'lit' + str ( '1243' ) . zfill ( 7 )
print ( empId )
[litindia@localhost demo]$ python [Link]
lit0001243
Translate method
[Link](table)
Translate method return a copy of the string S in which each character has been mapped through the
given translation table. The table must implement indexing for instance a dictionary or list, mapping
Unicode ordinals to Unicode ordinals, strings, or None.
Let’s go for an example how to use translate method using translation table.
strObject = 'Axi Byzthon'
print ( strObject )
table = { 65 : 'H', 66 : 'P', 120 : None , 122 : None }
print ( strObject . translate ( table ) )
[litindia@localhost demo]$ python [Link]
Axi Byzthon
Hi Python
From the above program we can identify that, A (65) is converted to H, B ( 66 ) is converted to P, and x (
120 ) , z ( 122 ) is converted to None ( deleted ).