Back to Study material
PPS

Unit – 4

Strings

 

 


In Python str class (string) represent string data type.

A String is a sequence of characters enclosed within single quotes, double quotes &sometimes triple quotes.

Eg)  S1= ‘firstYear’

        S2 = “firstYear”

 

But by using single quotes or double quotes we cannot represent multi line string literals.

          S1= ‘firstYear in SAE’-it will cause errors

For this requirement we should use triple quotes(either single or double)

            S1= ““firstYear in SAE”” or S1= “““firstYear in SAE”””

Through this triple quotes we can also embed one string into another string.

‘“These days “Python” is very powerful”’

Operations on strings: we can do various operation on string using different operators.

Concatenation: ‘+’ operator is used in python as well as various programming

languages to concatenate the string/s.

eg) print(“SAE” + “kondhwa”)

o/p)  SAEkondhwa

if need a space between string put it after first string ends or before second string starts

eg)  print(“SAE_” +“kondhwa”)

op)  SAE kondhwa

or

print(“SAE”+ “kondhwa”)

Multiplication: ‘*’operator is used for multiplying the string with represent to integer number.

Eg) print(‘SAE’*3)

O/p)  SAESAESAE        (can put spaces)

Print(‘SAE’*3)

o/p)  SAE SAESAE

in this we can use multiplier either of the string

 represented by [] (open close sequence brackets,

Note that in python strings follows zero based index.

Index can be +ve or –ve

 +ve index means from left to right billes

-ve index means backword from right to left.

        -ve-6          -5          -4           -3          -2         -1       

 

P

Y

t

h

o

N

 

 

Eg)

+ve0             1           2           3             4          5 

Code

>>> s=”python”

>>> s[0]

‘p’

>>> s[1]

‘y’

>>> s[-1]

‘n’

>>> s[7]   # error

Index Error : String index out of range.

>>> s[1:7]  # no error

‘ython’

>>> s[1:]                   # if no end mention then

‘ython’    #consider as all leftover

 

>>> s[:]  # no start and end mention

‘python’ # so complete string as o/p

 

>>>len(s)

6

 

Note: str (string) considered as one of fundamental data type in python.

 

In python we represent char also by ‘str’ class ,explicit char type is not available in

 

Str () : we can use this method to convert other type of values to str type

 

Eg)

>>> str(10)

‘10’ # this is not a integer

>>> str(10.7)

‘10.7’ #this is not a float but string likewise we can type cast any data types into string using str().

 


In python all fundamental  data types are immutable ,means when we creates an objects, we can not perform any changes to that object. If we do so  it means new object will be created. this non changeable behavior is called immutability,so str(string) is also a immutable object.

Eg)  s=’python’  # one object s

s=’java’  # new object s 

s=’c++’  # another new object s

s=’python’+ ‘java’ +’c ++’ # again new obj.

 

 

String formatting operator (%):

Formats the string an ording to the specified format.

Syntax:

  % [key][flags][width][precision][length type]conversion type % values.

 % : required the ‘%’char, which marks the start of the specifier

 Key: optional mapping key, consisting of a paranthessedsequence of characters

Flags: optional, conversion flags which affect the result of same conversion types

Width: optional, min field with, if specified as an * (asterisk), the actual width is read from the next dement of the triple.

In values, and the object to convert comes after the min field with and optional precision.

-precision: optional, precision gives as a ’ .’ (dot) followed by the  precision

 Length type: optional length modifier

Conversion type: optional, conversion type

*- values: required a number string or a container with values to substitute for conversion type.

 


‘ # ’: the value conversion will use the ‘alternate form’

 

‘ 0 ’:the conversion will be zero padded for numeric values

 

‘_’:the converted values is left adjusted(overrides the ‘0’conversion if both are given

“ (a space):a blank should be left before a positive number (a empty string) produced by signed conversion.

‘+’: A signed char (‘+’ or ‘-’)will precede the conversion (overrides a space flag)

Conversion types:

‘d’: signed integer decimal

‘i’: signed integer decimal

‘o’:signed octal value

‘u’:obsolete type-it is identical to ‘d’

‘x’ or’X’:signed hexadecimal. alternate form ox or oX

‘e’ or ‘E’: floating point exponential format

‘f’ or ‘F’: floating point decimal format

‘c’: single character

‘r’: string (converts and python obj using repr())

‘s’: string (converts any python obj using str())

%: no argument is converted; result in a %char in the result.

 

Ex) Subsititution

 

>>>‘%d’ % 100

                  ‘100’

>>>  ‘%d’ % ob1111

                   ‘15’

>>> ‘%s’ % ‘foo’

                    ‘foo’

>>> ‘%s %s’ % (‘foo’,’bar’)

                    ‘foo bar’

>>>dct ={‘foo’ : 10, ‘bar’: 20}

>>>’%(foo)s’ %dct

                          ‘10’

 

 

 

 

Ex2) 0(zero) padding

>>> ‘%d’ %1

‘1’

>>> ‘%3d’ %1

                              ‘001’

 

Ex3)    left adjust flag

>>> ‘%d’ %1

                              ‘1’

>>> ‘%d-5d’ %1

                              ‘1               #four spaces after 1

 >>> ‘%d 0-5d’ %1

                              ‘1               #same as above.

 

Ex 4)

 

usage of sign flag

>>> ‘%d’ %1

                              ‘1’

>>> ‘%+d’ %1

                              ‘+1’

 >>> ‘%+d ’ %-1

                              ‘-1’       

 >>> ‘%+d’ %-1         #space d

                              ‘-1’

 >> ‘% +d ’ %1

                              ‘+1’ 

 

Ex5) precision modifier

>>> ‘%f’ % 3.14

                              ‘3.140000’

>>> ‘%.1f ’ %3.14

                              ‘3.1’

 

Ex7 how to convert signed integer decimal

>>> ‘%1’ % ob1111

                              ‘15’

>>> ‘%d’ % ob1111

                              ‘15’

 >>> ‘%d  %10

                              ‘10’       

 >>> ‘%d’ %3.14       

                              ‘3’ 

 >>>‘%i’ %3.14

                              ‘3’ 

>>  ‘%i’ % -10

                              ‘-10’ 

 

Ex8)   hex and octal conversions

>>> ‘%x’  %27

                              ‘1b’

>>> ‘%X’ %27

                              ‘1B’

 >>> ‘%O  %10

                              ‘33’       

 

 

Ex9) character & string conversions

>>>‘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’

 

 


We have more than 40 methods applicable in ‘str’ class. various function does various task. We will see some of the methods herewith

 

Eg1)  capitalize() :Make capitalized case string

 

         Code:     s =’SAE kondhwa’

                     Print(s.capitalize())

               o/p: saekondhwa

 

Eg2) count() :count the occurrences of substring in main given string

 

         Code:     s =’SAE kondhwa’

                     Print(s.count(‘sae’))   #o/p=0

                     Print(s.count(‘SAE’))   #o/p=1

 

 

Eg 3)  isdecimal() : whether complete string is decimal or not.it returns true if string is decimal number otherwise false

 

         Code:     s =’SAE kondhwa’

                     Print(s.isdecimal ())   #false

 

                      S=’1 2 3 4 5 6’

                     Print(s. isdecimal ())   #True

 

Eg 4:  join() : returns concatenated with the elements of an iterable.

                     The join()method provides a flexible way to concatenates string.it concatenate each element of an irerable (such as list, string, triple) to the string and returns the concatenated string.

 

Syntax:                 string join (iterable)

 

Return value from join()

-          The join method returns a string concatenates with the elements of an iterable

-          If the iterable contains any non-string value it raises a typeErrorexeption.

 

 

 

Code 1:

numList =[‘1’,’2’,’3’,’4’]

                  separator=’,’

 

                print(separator.join(numList))

 

         o/p: 1,2,3,4           #but as a string

 

 

code 2:          s1=’ABC’

                      s2=’123’

 

                print(‘s1.join(s2):’,s1.join(s2))

               o/p s1.join(s2):1ABC2ABC3ABC

 

               print(‘s2.join(s1):’,s2.join(s1))

               o/p s2.join(s1): A123B123C123            #but its string

 

 

 


We can split the given string according to specified separator by using split () method.

 

Syntax:

Str.split(separator)

Note: Default separator is space.the return type of split() method is

Eg)

Code 1:

                S= ‘SAE kondhwa IT  dept’

 

                li= s. split()

               For   word in li:

                       Print(word)

 

o/p : SAE

kondhwa

 

Ord(): Given a string of length one ,return an integer representing the           Unicode ,code point of the character when the argument is a Unicode object ,or the value of the byte when the argument is an 8-bit string.

Eg)

>>>ord(‘a’)

>>> 97                                   range [0,65535]

 

Chr():Return a string of one character whose ASCII code is the integer i

Eg)

>>>chr(97)

>>> ‘a’

  This is the inverse of ord().the argument must be in range [0,255]inclus

valueError will be raised if i outside the range

 

>>> ‘kondhwa’ in  s

                 True

>>> ‘pune’ in   s

                False

>>> ‘pune’ not in  s

                 True

>>> ‘SAE’ not  in   s

                False

We can also use ‘in’ and ‘not in’ operator strings using for loop or if-elses. Also knows iterating through the string.

 

Eg

)     s=’SAE kondhwa campus’

            For word in s:

             Print (word)

 

o/p)   SAE                  # will print all word available

Kondhwa          # in s with char by char

        campus

        print( s1> s2)     # True

        print( s1< s2)     # false

        print( s1!=s2)     # True 

 

while comparing string we can also use identify operators like ‘is’ or ‘is not’

 

Eg)

>>> s1= ‘pune’

>>> s1= ‘mumbai’

>>> s1 is  s2

       False

>>> s1 is not s2

      True

 

Note: ‘= =’ and ‘is’  operator look like same as per their o/p but both

             Works differently.

Eg)

      >>>a= 1000

>>>b= 1000

>>>a== b

                 True

>>>a is b

                 False

 

Understand that ‘==’operator checks contents of an objects where ‘is ’ operator checks references (memory location) of an objects.

-it’s a built in module and we have to import it before using any of its constants and classes.

Code)

             import string  # module

               # string module constants

                Print(string.ascii_letters)  

                Print(string.ascii_lowercase)

                Print(string.ascii_uppercase)

                Print(string.digits)

                Print(string.hexdigits)

                Print(string.whitespace)

                Print(string.punctuation)

 

o/p:      a…….ZA………Z

           a………Z

          A………..Z

          0…………9

          0……9A…….F

                                      # new line as whitespace

                                      # & special char

! “#$%&’()*+,-./;:?@[\]_’{}

 


In operator

The ‘in’ operator is used to check if a value exists in a sequence or not. Evaluates to true if it finds a variable in the specified sequence and false otherwise.

Python program to illustrate

# Finding common member in list 

# using 'in' operator

list1=[1,2,3,4,5]

list2=[6,7,8,9]

for item in list1:

    if item in list2:

        print("overlapping")      

else:

    print("not overlapping")

 

Evaluates to true if it does not finds a variable in the specified sequence and false otherwise.

# Python program to illustrate

# not 'in' operator

x = 24

y = 20

list = [10, 20, 30, 40, 50 ];

  

if ( x not in list ):

   print "x is NOT present in given list"

else:

   print "x is  present in given list"

  

if ( y in list ):

   print "y is present in given list"

else:

   print "y is NOT present in given list"

 


To compare two strings, we mean that we want to identify whether the two strings are equivalent to each other or not, or perhaps which string should be greater or smaller than the other.

This is done using the following operators:

a)      ==: This checks whether two strings are equal

b)     !=: This checks if two strings are not equal

c)      <: This checks if the string on its left is smaller than that on its right

d)     <=: This checks if the string on its left is smaller than or equal to that on its right

e)      >: This checks if the string on its left is greater than that on its right

f)        >=: This checks if the string on its left is greater than or equal to that on its right

 


In Python, while operating with String, one can do multiple operations on it. Let’s see how to iterate over characters of a string in Python.

# Python program to iterate over characters of a string

  

# Code #1

string_name = "geeksforgeeks"

  

# Iterate over the string

for element in string_name:

    print(element, end=' ')

print("\n")

  

  

# Code #2

string_name = "GEEKS"

  

# Iterate over index

for element in range(0, len(string_name)):

    print(string_name[element])

 

Reference Books

 

  1. R. G. Dromey, “How to Solve it by Computer”, Pearson Education India; 1st edition, ISBN-10: 8131705625, ISBN-13: 978-8131705629 Maureen Spankle, “Problem Solving and Programming Concepts”, Pearson; 9th edition, ISBN-10: 9780132492645, ISBN-13: 978-0132492645
  2. Romano Fabrizio, “Learning Python”, Packt Publishing Limited, ISBN: 9781783551712, 1783551712
  3. Paul Barry, “Head First Python- A Brain Friendly Guide”, SPD O’Reilly, 2nd Edition, ISBN:978-93-5213-482-3
  4. Martin C. Brown, “Python: The Complete Reference”, McGraw Hill Education, ISBN-10: 9789387572942, ISBN-13: 978-9387572942, ASIN: 9387572943
  5. Jeeva Jose, P. Sojan Lal, “Introduction to Computing & Problem Solving with Python”, Khanna Computer Book Store; First edition, ISBN-10: 9789382609810, ISBN-13: 978-9382609810

 


Index
Notes
Highlighted
Underlined
:
Browse by Topics
:
Notes
Highlighted
Underlined