The group/sequence of characters is known as String. To represent the string in python we use 'str' datatype. We can create the string object in python in 2 ways, they are - by using ' ' and by using ''' '''.
Note - By using ' ' we can represent only one line string. By using ''' ''' we can represent multiple lines string.
String objects are immutable objects. Once if we create string object in some content later we cannot modify the content of that object. Every character in the string object is represented with unique index. Python supports both forward and backward indexes. x="rakesh"
0 r -6
1 a -5
2 k -4
3 e -3
4 s -2
5 h -1
We can access the characters of the string object by using their indexes.
Example -
x='rakesh'
print x
print type(x)
print id(x)
print x[2]
print x[4]
print x[-2]
print x[-5]
Output -
rakesh
<type 'str'>
45247072
k
s
s
a
If the given index is not available in the string we will get index error.
Example - print x[-8]
len() - It is used to know the length of string, list, tuple, set, dictionary and so on.
Example -
x='rakesh'
print x
print len(x)
Output -
rakesh
6
If we try to modify the content of string object by using index we will get the type error.
x='rakesh'
x[0]='a' // type error
String Slicing - Colon(:) is a slice operator, which is used to extract the require content from the string.
Example 1-
x='rakeshkumar'
print x
print type(x)
print id(x)
y=x[3:]
print y
print type(y)
print id(y)
z=x[2:6]
print z
a=x[3:-2]
print a
b=x[-5:-2]
print b
c=x[5:-9]
print c
d=x[6:2]
print d
e=x[12:]
print e
Output -
rakeshkumar
<type 'str'>
20540000
eshkumar
<type 'str'>
46776160
kesh
eshkum
kum
Example 2 -
x='Rakesh \
Kumar \
Guwahati'
print x
y='Rakesh\n\
Kumar\n\
Guwahati'
print y
z='''Rakesh
Kumar
Guwahati '''
print z
Output -
Rakesh Kumar Guwahati
Rakesh
Kumar
Guwahati
Rakesh
Kumar
Guwahati
No comments:
Post a Comment