0% found this document useful (0 votes)
11 views

String Datatype in Python

Uploaded by

Ananya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

String Datatype in Python

Uploaded by

Ananya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Strings in Python

Ques : What is a String? What are the different ways to create a String in Python?
A string is a sequence of characters. A String in python can be created using single quotes (''),
double quotes ("") and triple quotes (' ' ') / ( " "" ) . When we use triple quotes, strings can span
several lines without using the escape character.
Example:
st r1 = ' H el l o, " H ow ar e yo u " ? '
st r1 = "H el l o, \ " H ow a r e y ou \ " ? "
st r1 = '' ' H el l o, " H o w a r e y ou " ? '' '
st r1 = "" " H el l o, " H o w ar e y ou " ? " ""
st r2 = "C om pu t e r \ n Appl i cati on s "
st r3 = "" " Of fi ci al w e bsi te o f Py th on l an g u ag e i s:
h ttp:// ww w. py th on . o rg/ "" "

Ques : How are the indexes allotted in a String in Python? How can we access
individual characters in a String in Python?
Python indexes the characters in a string from left to right and from right end to left. From left
to right, the first character of a string has the index 0 and from right to left, the first character
of a string is –1. Individual characters in a string can be accessed by specifying the string name
followed by the index number in square brackets ([]).

Index from left 0 1 2 3 4 5 6 7

String/Characters C O M P U T E R

Index from right end –8 –7 –6 –5 –4 –3 –2 –1

st r1 = 'C O MP UT E R'
pri n t ( st r 1[0]) # 'C '
pri n t ( st r 1[7]) # 'R '
pri n t ( st r 1[3]) # 'P '
pri n t ( st r 1[ - 6] ) # 'M '
pri n t ( st r 1[ - 4] ) # 'U '
pri n t ( st r 1[ - 1] ) # 'R '

Ques : What is String Concatenation ? Give Example.


Concatenation means joining two String operands by linking them end-to-end. + Operator
concatenates two quoted strings with each other and produces a third string.
Example :
pri n t( 'H el l o! ' + 'F ri e n ds ') # ' H el l o!Fri en d s '

Ques : Predict the output of the following


fi rs t = ' On e '
s ec on d = ' Tw o '
pri n t ( fi r st+ s e c on d ) ____ ___ ____ ___ __ __
on e = ' 1 '
tw o = '2 '
pri n t ( on e +t w o) ____ ___ ____ ___ __ __
pri n t (i n t( on e) +i n t(t wo )) ____ ___ ____ ___ __ __

Page 1 of 7
Strings in Python
Ques : How can you replicate a String? Give example.
String can be replicated any number of times with the asterisk "*" operator.
st rA = 'P yth on '
pri n t ( st r A*4) # 'P yth on P yth on P yt h on Pyt h o n ‘
pri n t ( ' =' * 3 0) # '= == = == == == = == == == == == == = == == == '

Ques : Explain the use of Membership operators.


The membership operators are used to test whether a value is found in a sequence (string, list,
tuple, set and dictionary). There are two types of membership operators.

Operator Description

in The in operator tests if one string is present in another string. If a string exists then it
returns True, otherwise False. For example,

st r1 = "P yth on i n C BS E Sc h o ol s "


pri n t( 'C ' i n st r1 ) # Tr u e
pri n t( 'CB S E ' i n st r1 ) # Tr u e
pri n t( 'c bs e ' i n st r 1) # Fal s e

not in The not in operator evaluates True if it does not find a sub string in the specified
sequence, otherwise False. For example,

st r1 = "P yth on i n C BS E Sc h o ol s "


pri n t( 'C ' n o t i n st r1 ) # Fal s e
pri n t( 'CB S E ' n ot i n s tr1 ) # Fal s e
pri n t( 'H el p ' n ot i n s tr1 ) # Tr u e

Ques : Explain the use of Identity operators.


Identity operators compare the memory locations of two objects. There are two Identity
operators as explained below –

Operator Description

is Is operator evaluate to True if the variables on either side of the operator point to the
same object and False otherwise.

s1 = s2 = "h rm s"
s1 i s s2 #T ru e

s1 is s2, results in True since id(s1) equals id(s2).

is not Is not operator evaluate to False if the variables on either side of the operator point
to the same object and True otherwise.

s1 , s2 = "h an s ”, "r a j "


s1 i s n ot s2 # T ru e

s1 is not s2, results in True since id(s1) is not equal to id(s2).

Page 2 of 7
Strings in Python
Ques : How can we compare two Strings in Python?
Strings can be compared with the relational (comparison) operators ==, !=, <, >, <= , >=
These comparisons use the standard character-by-character comparison rules for ASCII or
Unicode. The comparison operator returns a Boolean result True or False.
Operator Name Str1 = "Py", Result
Str2 = "Python"
== Equal to Str 1= =St r2 False
!= Not equal to Str 1!= St r2 True
> Greater than Str 1> St r2 False
< Less than Str 1< St r2 True
>= Greater than or equal to Str 1> = St r2 False
<= Less than or equal to Str 1< =St r2 True

Ques : What do you mean by Strings are Immutable?


Strings are immutable means we cannot change individual characters within a string. However,
we can concatenate a String with another String.
Example:
st r1 = "P yth on i n C BS E Sc h o ol s "
st r1[ 0] = ' M ' # Invalid Error : 'str' object does not support item assignment
st r1 = "M y " +st r 1 # Valid: This is just simply concatenate two strings
pri n t( st r1) # prints : 'My Python in CBSE Schools'

Ques : How do you slice a String in Python?


A substring of a string is called a slice. Subsets of strings can be taken using the slice operator
with [start : stop : step] in square brackets separated by a colon. It extracts the part of the
string from the start position and up to but not including stop position, i.e., stop –1.

0 1 2 3 4 5 6 7 8
H a p p i n e s s
-9 -8 -7 -6 -5 -4 -3 -2 -1

str1 = 'Happiness' # original string


Example Result Explanation
pri n t ( st r 1[0] ) H Prints 0th character
pri n t ( st r 1[1] ) a Prints 1st character
pri n t ( st r 1[3: 6] ) pin Prints 3rd to 5th character
pri n t ( st r 1[:4] ) Happ Prints 0th to 3rd character
pri n t ( st r 1[1:] ) appiness Prints 1st to last character
pri n t ( st r 1[1: - 3] ) appin Prints 1st to -4th character
pri n t ( s t r 1[ - 3: ] ) ess Prints -3rd to last character
pri n t ( st r 1[ - 7: - 3] ) ppin Prints -7th to -4th character
pri n t ( st r 1[0: 8:2 ] ) Hpie Prints every 2nd character from 0th to 7th character
pri n t ( st r 1[ : : 2 ] ) Hpies Prints every 2nd character from 0th to last character
pri n t ( st r 1[ - 8: - 2:2 ] ) apn Prints every 2nd character from -8th to -2nd character
pri n t ( st r 1[8: 2: - 2] ) sei Prints every 2nd backward character from 8th to 2nd character
pri n t ( st r 1[ - 1: - 9: - 2 ] ) seip Prints every 2nd backward character from -1st to -9th character

Page 3 of 7
Strings in Python
Operator Description
Ques: Consider the following string and Write statements for the following:

n e w_ st r = " In t el l ect u al Capi tal "


(a) To display the last seven characters.
_________________
(b) To display substring starting from index 5 and ending at index 12.
_________________
(c) To print the last four characters from the string.
_________________
(d) To print the first four characters from the string.
_________________

Ques: Explain the use of various String functions in Python.


A string object has a number of functions with different parameters. The dot operator (.) is used
along with the string to access string functions except len() function.

Function Description
len(str) Returns length of string str. Length includes white spaces.

pri n t ( l e n ( 'B e G o o d')) #7


s = '\ ''
pri n t ( l en ( s)) #1
dt = '2 8th Ju l y, 2 01 8'
pri n t ( dt [ l e n ( dt) - 4 : ] ) #2 018

str.capitalize() Capitalizes the first letter of the str.

st r = ' pyt h on p r og r a m'


pri n t ( s t r .c api tal i z e()) # 'P yth on p r og ra m'

str.find (sub, start, end ) Returns the index of the substring sub if found in a string str. If not
found, it returns -1.
sub - It's the substring to be
searched in the string str. st r = ' pyt h on p r og r a m'
start – where to begin the pri n t ( st r .fi n d ('p ') ) # 0
search. starting index is pri n t ( st r .fi n d ('p ' , 5)) # 7
pri n t ( st r .fi n d (' s ')) # -1
assumed to be 0 if not given
pri n t ( st r .fi n d (' P ')) # -1
end – ending index assumed pri n t ( st r .fi n d ('p r o g')) #7
as length of str if not given
str.count (sub, start, end ) Returns the number of occurrences of a substring sub in the given
string str.
sub - It's the substring to be
searched in the string str. st r = ' st ri n g i s i mm u tabl e '
pri n t ( st r .c ou n t ( 'i ' )) #3
Page 4 of 7
Strings in Python
start – starting index, pri n t ( st r .c ou n t ( 'i ' ,5)) #2
assumed to be 0 if not given va r = ' Th i s i s an e x ampl e '
end – ending index, pri n t ( va r .c ou n t ( 'i s' )) #2
assumed as length of str if pri n t ( va r .c ou n t ( 'i s' ,5 )) #1
not given
str.isalnum() Returns True if all characters in the string str are alphanumeric
(either alphabets or numbers). If not, it returns False.

n am e = ' Ch a rl e s1 23 '
pri n t(n a m e.i s al n u m( )) # T ru e
n am e= ' Ch a rl e s 1 2 3'
pri n t(n a m e.i s al n u m( )) # Fal s e ( co n tai n s spa c e)
pri n t(" 123 " .i sal n u m ()) # Tru e
n am e= ' Ch a rl e s @12 3 '
pri n t(n a m e.i s al n u m( )) # Fal s e ( co n tai n s @ )

str.isalpha() Returns True if all characters in the string str are alphabets. If not,
it returns False.

pri n t ( "12 3" .i sal ph a() ) # Fal s e


pri n t ( "h rm s ".i s al ph a()) # T ru e
gen d er = ' M'
pri n t ( g en d e r .i sal ph a()) # T ru e

str.isdigit() Returns True if all characters in a string str are digits. If not, it
returns False.

ph on e = "1 234 5"


pri n t( ph on e.i s di gi t() ) # T ru e
ph on e = "91 - 123 45 "
pri n t( ph on e.i s di gi t() ) # Fal s e

str.isupper() Returns True if all characters in a string str are in uppercase.


If not, it returns False.

pri n t ( " H rm s ".i su pp e r()) #Fal s e


pri n t ( " HR MS ".i su pp e r()) # T ru e

str.islower() Returns True if all characters in a string str are in lowercase.


If not, it returns False.

pri n t ( " H rm s " .i sl o w e r()) # Fal s e


pri n t ( "h rm s ".i sl o w e r()) # T ru e
pri n t ( "h rm s1 23 ".i sl ow e r ()) # T ru e

Page 5 of 7
Strings in Python
str.isspace() Returns True if there are only whitespace characters in the string
str. If not, it return False.

st r= ' '
pri n t ( st r .i ss pa c e() ) # T ru e
st r= ' \t '
pri n t ( st r .i ss pa c e() ) # T ru e
st r= ' \n '
pri n t ( st r .i ss pa c e() ) # T ru e
st r = ' wel c o m e '
pri n t ( st r .i ss pa c e() ) #F al s e
st r = ' '
pri n t ( st r .i ss pa c e() ) #F al s e

str.lower() Converts all uppercase characters in a string str into lowercase


characters and returns it.

pri n t ( " H rm s ".l o w e r () ) #h r ms

str.upper() Converts all lowercase characters in a string str into uppercase


characters and returns it.

pri n t ( " H rm s ".u pp e r () ) # H RMS

str.lstrip() It returns the string after removing the spaces on the left of str.

st r = ' H an sr aj S ch o ol '
pri n t ( st r) # H an s r aj S ch o ol
pri n t ( st r .l st ri p() ) # H an s raj S ch o ol

str.rstrip() It returns the string after removing the spaces on the right of str.

st r = ' Han s raj Sc h o ol '


pri n t ( l en ( st r)) #27
pri n t (l en ( st r. r st ri p( ))) #17

str.replace(old, new, max) Replaces all the occurrences of substring ‘old’ with ‘new’ in the
string str. ‘max’ is the maximum no, of replacements

st r = ' w o rk i s w o r sh i p'
pri n t ( st r . r epl ac e (' w ', ' W ')) # W o rk i s W o r sh i p
pri n t ( st r . r epl ac e (' ' ,' # ')) # wo r k #i s# wo r sh i p
a = "T h i s i s i sl an d o f i st an bu l "
pri n t ( a. r e pl ac e( "i s" ," wa s" , 3 )) # Thwas was wasland of istanbul

Page 6 of 7
Strings in Python
Ques: Observe the following assignment statement and answer the questions that
follow:
str = '''be
the change'''

a) Write the Positive and Negative Index Numbers of str.

b e \n t h e c h a n g e

b) Give the output of the following statements:


1. pri n t ( 'h ' i n st r ) ____ ___ ____ ___ __ ____ __
2. pri n t ( 'n a' i n st r) ____ ___ ____ ___ __ ____ __

3. pri n t ( 'h e ' n ot i n st r ) ____ ___ ____ ___ __ ____ __


4. pri n t ( st r[2 ]+ ' ?' ) _____ ___ ___ ____ _ ____ __
5. pri n t ( st r[3 :6] + 'a tr e ' ) _____ ___ ___ ____ _ ____ __
6. pri n t ( st r .c api tal i z e() ) _____ ___ ___ ____ _ ____ __
7. pri n t ( l en ( st r) ) ____ ___ ____ ___ __ ____ __
8. pri n t ( st r[ - 6:] * 3 ) ____ ___ ___ _ ___ __ ____ __
9. pri n t ( st r[ - 5] ) _____ ___ ___ ____ _ ____ __
10. pri n t ( st r[ - 5:] .i sl o w er ()) ____ ___ ____ ___ __ ____ __
11. pri n t ( st r[ l en ( st r) - 6: ] ) ____ ___ ____ ___ __ ____ __
12. pri n t ( st r .c ou n t(' e ') ) ____ ___ ____ ___ __ ____ __
13. pri n t ( st r .c ou n t(' e ' , 5) ) ____ ___ ____ ___ _ _ ____ __
14. pri n t ( st r .fi n d( 'h e' ) ) ____ ___ ____ ___ __ ____ __
15. pri n t ( st r .u pp e r() ) ____ ___ ____ ___ __ ____ __
16. pri n t ( st r .r e pl ac e( ' be ' ,' s e e ')) ____ ___ ____ ___ __ ____ __
17. pri n t ( st r .i sal n u m() ) ____ ___ ____ ___ __ ____ __

Ques: Predict the output of the following statements:


a) su b = "i n f o r m ati cs p ra cti c e s " . rst ri p() + " 06 5 ". l stri p()
pri n t ( su b .u pp e r( )) ____ ___ ____ ___ __ ____ __

b) a dd r es s = "R o ad N o .73 , Pu n j abi B agh "


pri n t ( a dd r e ss .i s sp ac e() ) ____ ___ ____ ___ __ ____ __
pri n t ( a dd r e ss .i sal n u m()) ____ ___ ____ ___ __ ____ __
pri n t ( a dd r e ss .i sdi g i t()) ____ ___ ____ ___ __ ____ __
pri n t ( a dd r e ss .i sal p h a()) ____ ___ ____ ___ __ ____ __

Page 7 of 7

You might also like