Strings
Strings
Output
spam eggs
doesn't
doesn't
"Yes," they said.
"Yes," they said.
"Isn't," they said.
Empty String
word =’’
or
word=””
or
word=str()
Indexing
Strings can be indexed (subscripted), with the first character having index
0. There is no separate character type; a character is simply a string of size
one:
word ='Python'
print(word[0])# character in position 0 output P
print(word[5])# character in position 5 output n
Indices may also be negative numbers, to start counting from the right:
word ='Python'
print(word[-1])# last character n
print(word[-2])# second-last character o
print(word[-6]) P
Python Strings are Immutable
word ='Python'
word[0]='J'
TypeError: 'str' object does not support item
assignment
Traversing a string
Traversing a string means accessing all the elements of the string one after
the other by using the subscript. A string can be traversed using a ‘for’ loop
or a ‘while’ loop.
Word =’Python’
# Traversal using for loop
for i in word:
print(i)
Output:
P
y
t
h
o
n
# Traversal using while loop- can access index
and character both
i =0
while i <len(word):
print( word[i])
i = i +1
P
y
t
h
o
n
Multiline Strings/Docstrings
To output the string on multiple lines
Operations on String
Concatenation (+)
Strings can be concatenated (glued together) with the + operator. Both the
operands should be of string datatype else it results in an error
Repetition/Replication (*)
Strings can be repeated with the * operator where one operand is the string
and the other operand is an integer:
The in operator returns the boolean value True if the string contains the
given character or the sequence of characters and vice-versa for the case
of not in operator.
Slicing (str[m:n])
print(word[-len(word):]) #Python
print(word[1:7:2]) #yhn
print(word[::-2]) #nhy
print(word[-6:-1:2]) #Pto
Note:
Slicing rules:
a)if index traverses from LEFT -> RIGHT & STEPVALUE is +ve,it takes
from left to right.If step value is -ve it gives empty string as shown in last 2
examples here
eg) s=’Python’
s[1:5:2] - output: 'yh'
s[:3:1] - output: ‘Pyt’
s[1:5:-1] - ‘’
s[0:5:-2] - ‘’
c)If either start or end index is omitted and step value is negative,it
displays the characters in reverse.
Eg1) N="Python Examination"
N[:8:-1] - 'noitanima'
N[8::-1] - 'xE nohtyP'
N[:8:-2] - 'niaia'
N[8::-2] - 'x otP'
d)If the index that is not in range is given in slicing,it does not
generate an error.It gives an EMPTY STRING
s=”Python”
s[100:45:-1] - ‘’
s[10:7] - ‘’
s[7:12] - ‘’
word ='Python'
print(len(word))
6
2)string.capitalize(word)
Return a copy of word with only its first character capitalized and the
remaining characters changed to lowercase.
5)str.isalpha()
Return true if all characters in the string are alphabetic and there is at least
one character, false otherwise.
word ='apparatus123'
print(word.isalpha())# Returns False as it
contains numeric values
word ='apparatus'
print(word.isalpha())# Returns True
word ='apparatus abc'
print(word.isalpha())# Returns False as it has a
space
6)str.isdigit()
Return true if all characters in the string are digits and there is at least one
character, false otherwise.
word ='displace123'
print(word.isdigit()) False
word ='123'
print(word.isdigit()) True
7)str.lower()
Returns the exact copy of the string with all the letters in lowercase.
word ='fUnCtIonAl jUnGlE'
print(word.lower())
functional jungle
8)str.islower()
Returns True if the string is in lowercase else returns False.
word ='Python'
print(word.islower()) ---- False
word ='python is a prog lang'
print(word.islower()) ----- True
9)str.isupper()
Returns True if the string is in uppercase.
word ='PYTHON'
print(word.isupper()) --- True
word ='python'
print(word.isupper()) --- False
10)str.upper()
Returns the exact copy of the string with all letters in uppercase.
11)str.isspace()
Returns True if the string contains only whitespace characters.
Str1=’ abc’
print(Str1.isspace()) -------- False
Str2=’ ‘
print (Str2.isspace()) --------- True
word ='Python'
print(word.isspace()) ---------- False
12)str.lstrip([chars])
Return a copy of the string with leading characters removed. The chars
argument is a string specifying the set of characters to be removed. If
omitted or None, the chars argument defaults to removing whitespace. The
chars argument is not a prefix; rather, all combinations of its values are
stripped
13)str.rstrip([chars])
Return a copy of the string with trailing characters removed. The chars
argument is a string specifying the set of characters to be removed. If
omitted or None, the chars argument defaults to removing whitespace. The
chars argument is not a suffix; rather, all combinations of its values are
stripped:
word ='mississippi'
print((word.rstrip('ippi')) output:'mississ'
15)str.istitle()
Return true if the string is a titlecased string and there is at least one
character, for example uppercase characters may only follow uncased
characters and lowercase characters only cased ones. Return false
otherwise.
word ='marsh exact'
print(word.istitle()) ---- False
word ='Marsh Exact'
print(word.istitle())--------- True
Return a copy of the string with all occurrences of substring old replaced by
new. If the optional argument count is given, only the first count
occurrences are replaced.
print(word.replace('mourning','happy',2))#
Replaces only 2 occurence of mourning
Output:
happy silver happy silver silver mourning silver
18)str.join(iterable)
19)str.swapcase()
21)str.split([sep[, maxsplit]])
The function splits the string into substrings using the separator. The
second argument is optional and its default value is zero. If an integer value
N is given for the second argument, the string is split in N+1 strings.
word ='linear$pit$syndrome$cottage$fitness'
print(word.split('$',3))
Output:
['linear', 'pit', 'syndrome', 'cottage$fitness']
22)count()-It returns the number of times substring occurs in the
given string.If the start index and end index are not given,it starts
from 0 till the length of the string.
26)ord() 27)chr()
2)
Ans: