Ch-6 Notes and Questions
Ch-6 Notes and Questions
STRINGS IN PYTHON
Indexing: One way is to treat strings as a list and use index values.
Example –
greet = 'hello'
Example –
greet = 'hello'
Example –
greet = 'Hello'
Example –
message = 'Hola Amigos'
message[0] = 'H'
print(message)
Output:
TypeError: 'str' object does not support item assignment
Multiline String
We can also create a multiline string in Python. For this, we use triple
double quotes """ or triple single quotes '''.
Example –
# multiline string
message = """
Never gonna give you up
Never gonna let you down
"""
print(message)
Output:
Never gonna give you up
Never gonna let you down
String Operators
Operator Description
r/R It is used to specify the raw string. Raw strings are used in
the cases where we need to print the actual meaning of
escape characters such as "C://python". To define any
string as a raw string, the character r or R is followed by
the string.
Output:
HelloHelloHello
Hello world
o
ll
False
False
C://python37
The string str : Hello
Example -
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
Output: False
True
2. Concatenation Operator
Example -
greet = "Hello, "
name = "Jack"
# using + operator
result = greet + name
print(result)
Example -
print('a' in 'program')
print('at' not in 'battle')
# Output: True
False
Example –
hi = "goodforgood"
print(hi[::-1])
Output: doogrofdoog
slice(start,stop,step)
Example –
greet = 'Hello'
# Output: 5
Method Description
endswith() Returns true if the string ends with the specified value
find() Searches the string for a specified value and returns the
position of where it was found
index() Searches the string for a specified value and returns the
position of where it was found
isalpha() Returns True if all characters in the string are in the alphabet
isascii() Returns True if all characters in the string are ascii characters
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
partition() Returns a tuple where the string is parted into three parts
rfind() Searches the string for a specified value and returns the last
position of where it was found
rindex() Searches the string for a specified value and returns the last
position of where it was found
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
Note: All string methods returns new values. They do not change the original
string.
1. s.capitalize()
Capitalizes a string
Output
Hello buddy
2. s.lower()
Converts all alphabetic characters to lowercase
Output
hello buddy
3. s.upper()
Converts all alphabetic characters to uppercase
Output
HELLO BUDDY
4. s.title()
Converts the first letter of each word to uppercase and
remaining letters to lowercase
Output
Hello Buddy
5. s.swapcase()
Swaps case of all alphabetic characters.
Output
‘HEllO bUdDy’
8. s.isalnum()
Returns True if all characters of the string are alphanumeric,
i.e., letters or numbers.
>>> s = "Tech50"
>>> s.isalnum()
True
>>> s = "Tech"
>>> s.isalnum()
True
>>> s = "678"
>>> s.isalnum()
True
9. s.isalpha()
Returns True if all the characters in the string are alphabets.
>>> s = "Techvidvan"
>>> s2 = "Tech50"
>>> s.isalpha()
True
>>> s2.isalpha()
False
10. s.isdigit()
Returns True if all the characters in the string are numbers.
>>> s1 = "Tech50"
>>> s2 = "56748"
>>> s1.isdigit()
False
>>> s2.isdigit()
True
11. s.islower()
Returns True if all the alphabets in the string are lowercase.
>>> s1 = "Tech"
>>> s2 = "tech"
>>> s1.islower()
False
>>> s2.islower()
True
12. s.isupper()
Returns True if all the alphabets in the string are uppercase.
>>> s1 = "Tech"
>>> s2 = "TECH"
>>> s1.isupper()
False
>>> s2.isupper()
True
13. s.lstrip([<chars>])
Removes leading characters from a string.
Removes leading whitespaces if you don’t provide a <chars>
argument.
14. s.rstrip([<chars>])
Removes trailing characters from a string.
Removes trailing whitespaces if you don’t provide a <chars>
argument.
15. s.strip([<chars>])
Removes leading and trailing characters from a string.
Removes leading and trailing whitespaces if you don’t provide
a <chars> argument.
SOLVED QUESTIONS
1. What is a string?
Ans. A string is a sequence of characters where each character can be a letter, number or special symbol. We
can enclose characters in quotes (single, double or triple).
2. What is slicing in string?
Ans. Slicing returns the substring from the given string using slicing operator [:].
3. What is traversing astring?
Ans. Traversing a string means accessing each character one after the other by iterating through the elements
of astring using either for or while loop.
4. Write the output of the following statement:
strl = This is Mohit\'s "CS" book!
print (len (strl) )
Ans. 25
5. Consider the string str1="Green Revolution". Write statements in Python to implement the
following:
(a) To display the last four characters.
(b) To display the starting index for the substring 'vo'.
(c) To check whether the string contains 'vol' or not.
(d) To repeat the string 3 times.
Ans. (a) strl [ -4:]
'tion
(b) strl.find('vo')
8
(c)vol' in strl
True
(d) st.rl*3
'Greern Revolution Green Revolution Green
Revolution!
6. What will be the output of the following programming code?
X="AmaZing"
print (%|3:], "and", x[:2])
print (%[-7:], "and", x[-4:-2] )
print (x12:7],"and", x[-4:-1] )
Ans. Zing and An
ArnaZing and Zi
aZing and 2in
7. Consider the following code:
STR1=input ""Enter a string: ")
while len (STR1 )<=4:
if STR1 [-1] =='z':
STR1=STR1 [0:3]+'c!
elif 'a' in STR1:
STR1 = STR1 (0]+'bb!
elif not int (STR1 (0]):
STR1 = 'I'+STR1 [1:] +'z!
else:
STR1=STR1+ *
print (STR1)
What will be the output produced if the input is:
(a) lbzz (b) abcd
Ans. (a) 1bzc*
(b) endless loop because 'a' will always remain at index 0.
8. Write the output of the following code when executed:
Text=" gmail@com"
l=len (Text)
ntext="n
print(ntext)
Ans. GMAILbbCOM
9. How many times is the word HELLO' printed in the following statement?
S='python rocks!
for ch in s[3:8] :
print ('Hello')
Ans. 5 times
10
-1
11. How can you create an empty string?
IS. An empty string can be created by using either double quotes (" )or single quotes () and assigning it
to a variable.
12. Differentiate between indexing and traversing of string
index value is e
Ans. Indexing: Accessing individual characters of the string by using the subscript or
indexing. The indexspecifies thecharacter to be accessed in the string and is written in square brackets (1
Traversing: Accessing each character one after the other by iterating through the elements of a string using
either for or while loop.
13. Why is string an immutable data type?
that is why it is an imm.ot.
Ans. The contents of the string cannot be changed after it has been created;
data type.
For example,
Str1='Sound'
Str1[0]='P'
would result in - TypeError: 'str' object does not support item assignment.
14. A string called str1 contains whitespaces at the left of the string as given.
Python Program"
Write the command to delete the spaces.
Ans. The command is: strl.lstrip ()
15. What will be the value stored in bval upon execution if two strings strl and str2 are taken as "Delhi" and
"New Delhi"?
(i) bval = strl > str2 (ii) bval = strl.lower () < str2
Ans. (i) False (iü) False
16. Write a Python code to access each character, one by one, of string 'hello'.
Ans. Code:
for ch in hello :
print (ch)
Output:
17. Write a program tocount the number of vowels in the string 'pineapple'.
Ans. Code:
WOrd = 'pineapple'
Count = 0
for letter in word:
if letter in (i', u', 'a', 'e', 'o'):
Count=count+ 1
print (count)
Output:
4