String Data Type
Creating String
● Create String simply by enclosing characters in quotes
● Python treats single quotes the same as double
quotes.
● Creating strings is as simple as assigning a value to a
variable.
Eg.
– var1 = 'Hello World!'
– var2 = "Python Programming"
Accessing String
●
String is Sequence type
– as it consists of sequence of characters
●
Slices([ ],[ : ], [ : : ]):
Eg.
– Message=”Welcome to KIT”
– print Message[3] : prints 'c'
– Print Message[3:7] : prints 'come'
– Print Message[::-1] : Reverse the String
– Print Message[::2]: prints alternate characters
– print Message[:3]: prints 'Wel'
– print Message[3:]: prints 'come'
Updating Strings
● "update" an existing string by reassigning a variable
to another string
● The new value can be related to its previous value
or to a completely different string altogether.
● eg.
var1 = 'Hello World!'
print "Updated String :- ", var1[:6] + 'Python'
Output: Updated String :-Hello Python
Remove Characters and Strings
●
eg.
>>>string=”Hello World!”
>>>string = string[:3]+ string[4:]
>>>string
>>>'Helo World!'
>>>string=''
>>> string
>>> ''
>>>del string
>>> string (it will give the error)
String and Operators
>>>str1='abc'
>>>str2='lmn'
>>>str3='xyz'
>>>str1<str2
>>>True
>>>str2!=str3
>>>True
>>>str1<str3 and str2 == 'xyz'
>>>False
String Special Operators
String Formatting Operator
● string format operator %
● This operator is unique to strings and makes up for
the pack of having functions from C's printf family
Eg.
print "My name is %s and weight is %d kg!" % ('Zara',
21)
output: My name is Zara and weight is 21 kg!
● "%03d" % 1
● print "%*s"%(9,”hello”)
● '%d' % 100
● '%d' % 0b1111
● "%x" % 17
● "%#x" % 17
● "%-5d" % 1 '1 '
● "%0+5d" % 1 '+0001'
● '% d' % 1
● '%+d' % 1
● '%.1f' % 3.14
● '%f' % 10 # Float conversions. '10.000000'
● '%F' % 10 '10.000000'
● '%g' % 1234567890 '1.23457e+09'
● '%G' % 1234567890 '1.23457E+09'
● '%e' % 1234567890 '1.234568e+09'
● '%E' % 1234567890 '1.234568E+09'
● 'ABC %c' % 10 'ABC \n'
● 'ABC %c' % 67 'ABC C'
● 'ABC %c' % 68 'ABC D'
● 'ABC %c' % 'D' 'ABC D'
● 'ABC %s' % 68 'ABC 68'
● 'ABC %r' % 68 'ABC 68'
Unicode String
● Normal strings in Python are stored internally
as 8-bit ASCII, while Unicode strings are stored
as 16-bit Unicode
● Print u 'Hello, world'
Standard Type Functions
● cmp(str1,str2) :compares 2 strings
● len(str1): returns length of string
● max(‘lmn’): greatest character in string(lexicographic order)
● min(‘xyz’):least character in string(lexicographic order)
● enumerate(str1): assigns index to characters
● raw_input()
● str()
● chr(num)
● ord(chr)
Built-in String Methods
● [Link](): returns a copy of the string with
only its first character capitalized.
● [Link](width[, fillchar]): The method center()
returns centered in a string of length width.
Padding is done using the specified fillchar.
● [Link](sub, start= 0,end=len(string)): method
count() returns the number of occurrences of
substring sub in the range [start, end]
● [Link](encoding='UTF-8',errors='strict'):
returns an encoded version of the string
● [Link](encoding='UTF-8',errors='strict'):
decodes the string using the codec registered
for encoding. It defaults to the default string
encoding
– encoding − This is the encodings to be used
– errors − This may be given to set a different error
handling scheme. The default for errors is 'strict',
meaning that encoding errors raise a UnicodeError.
Other possible values are 'ignore', 'replace',
'xmlcharrefreplace', 'backslashreplace' and any
other name registered via codecs.register_error()
Str = "this is string example....wow!!!";
Str = [Link]('base64','strict');
print "Encoded String: " + Str
print "Decoded String: " +
[Link]('base64','strict')
● [Link](suffix[, start[, end]]): returns True if
the string ends with the specified suffix, otherwise
return False
– suffix − This could be a string or could also be a tuple of
suffixes to look for.
– start − The slice begins from here.
– end − The slice ends here
● [Link](str, beg=0, end=len(string)): It determines
if string str occurs in string, or in a substring of string
if starting index beg and ending index end are given
– str − This specifies the string to be searched.
– beg − This is the starting index, by default its 0.
– end − This is the ending index, by default its equal to the
length of the string.
● [Link](str, beg = 0 end = len(string)): It
determines if string str occurs in string or in a
substring of string if starting index beg and ending
index end are given. This method is same as
find(), but raises an exception if sub is not found.
● [Link]():checks whether the string consists
of alphanumeric characters
● [Link](): checks whether the string consists
of alphabetic characters only
● [Link](): checks whether the string consists of
digits only
● [Link](): checks whether all the case-based
characters (letters) of the string are lowercase.
● [Link](): checks whether the string
consists of only numeric characters. This method
is present only on unicode objects.
– str = u"this2009";
– print [Link]() False
– str = u"23443434";
– print [Link]() True
● [Link](): checks whether the string consists
of whitespace.
– str = " ";
– print [Link]() True
– str = "This is string example....wow!!!";
– print [Link]() False
● [Link](): istitle() checks whether all the
case-based characters in the string following
non-casebased letters are uppercase and all
other case-based characters are lowercase
– str = "This Is String Example...Wow!!!";
– print [Link]()
– str = "This is string example....wow!!!";
– print [Link]()
● [Link](): isupper() checks whether all the
case-based characters (letters) of the string are
uppercase.
● len( str ): returns the length of the string.
● [Link](sequence): returns a string in which the
string elements of sequence have been joined by
str separator.
– s = "-";
– seq = ("a", "b", "c"); # This is sequence of strings.
– print [Link]( seq ) #a-b-c
● [Link](width[, fillchar]): returns the string left
justified in a string of length width. Padding is
done using the specified fillchar (default is a
space). The original string is returned if width is
less than len(s).
– str = "this is string example....wow!!!";
– print [Link](50, '0')
● this is string example....wow!!!000000000000000000
● [Link](width[, fillchar]): returns the string right justified
in a string of length width. Padding is done using the
specified fillchar (default is a space). The original string is
returned if width is less than len(s).
● [Link](): returns a copy of the string in which all
case-based characters have been lowercased
● [Link](): returns a copy of the string in which all
case-based characters have been uppercased.
● [Link]([chars]): returns a copy of the string in which
all chars have been stripped from the beginning of the
string (default whitespace characters).
– str = " this is string example....wow!!! ";
– print [Link]()
– str = "88888888this is string example....wow!!!8888888";
– print [Link]('8')
● [Link]([chars]): returns a copy of the string
in which all chars have been stripped from the
end of the string (default whitespace
characters).
– str = " this is string example....wow!!! ";
– print [Link]()
– str = "88888888this is string example....wow!!!
8888888";
– print [Link]('8')
● [Link](intab, outtab): returns a translation table
that maps each character in the intabstring into the
character at the same position in the outtab string. Then
this table is passed to the translate() function
– intab − This is the string having actual characters.
– outtab − This is the string having corresponding mapping
character.
– from string import maketrans # Required to call maketrans
function.
– intab = "aeiou"
– outtab = "12345"
– trantab = maketrans(intab, outtab)
–
– str = "this is string example....wow!!!"
– print [Link](trantab) #th3s 3s str3ng 2x1mpl2....w4w!!!
● max(str): returns the max alphabetical
character from the string str.
● min(str): returns the min alphabetical character
from the string str.
● [Link](old, new[, max]): returns a copy of
the string in which the occurrences of old have
been replaced with new, optionally restricting
the number of replacements to max
– str = "this is string example....wow!!! this is really
string"
– print [Link]("is", "was") # thwas was string
example....wow!!! thwas was really string
– print [Link]("is", "was", 3) # thwas was string
example....wow!!! thwas is really string
● [Link](str="", num=[Link](str)):
returns a list of all the words in the string, using
str as the separator (splits on all whitespace if
left unspecified), optionally limiting the number
of splits to num
– str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
– print [Link]( ) :# ['Line1-abcdef', 'Line2-abc',
'Line4-abcd']
– print [Link](' ', 1 ) : # ['Line1-abcdef',
'\nLine2-abc \nLine4-abcd']
● [Link]( num=[Link]('\n')): returns a list
with all the lines in string, optionally including the line
breaks (if num is supplied and is true)
– num − This is any number, if present then it would be
assumed that line breaks need to be included in the lines.
– str = "Line1-a b c d e f\nLine2- a b c\n\nLine4- a b c d";
– print [Link]( ) ['Line1-a b c d e f', 'Line2- a b c', '',
'Line4- a b c d']
– print [Link]( 0 ) ['Line1-a b c d e f', 'Line2- a b c', '',
'Line4- a b c d']
– print [Link]( 3 ) ['Line1-a b c d e f\n', 'Line2- a b c\n',
'\n', 'Line4- a b c d']
– print [Link]( 4 ) ['Line1-a b c d e f\n', 'Line2- a b c\n',
'\n', 'Line4- a b c d']
– print [Link]( 5 ) ['Line1-a b c d e f\n', 'Line2- a b c\n',
'\n', 'Line4- a b c d']
● [Link](str, beg=0,end=len(string)):
checks whether string starts with str, optionally
restricting the matching with the given indices
start and end.
– str = "this is string example....wow!!!";
– print [Link]( 'this' ) True
– print [Link]( 'is', 2, 4 ) True
– print [Link]( 'this', 2, 4 ) False
● [Link]([chars]): returns a copy of the string in
which all chars have been stripped from the
beginning and the end of the string (default
whitespace characters)
– str = "0000000this is string example....wow!!!
0000000";
– print [Link]( '0' )
● [Link](): returns a copy of the string in
which all the case-based characters have had
their case swapped
– str = "this is string example....wow!!!";
– print [Link]()
– THIS IS STRING EXAMPLE....WOW!!!
● [Link](width): pads string on the left with zeros to fill
width.
– str = "this is string example....wow!!!";
– print [Link](40) # 00000000this is string example....wow!!!
● [Link](): checks whether the string consists of
only decimal characters. This method are present only
on unicode objects
– str = u"23443434";
– print [Link](); # True
● [Link](): returns a copy of the string in which first
characters of all the words are capitalized
– str = "this is string example....wow!!!";
– print [Link]()
– This Is String Example....Wow!!!