KnowledgeBoat Logo
|
OPEN IN APP

Chapter 15

Strings in Python

Class 10 - KIPS Robotics & AI



Activity 15.1

Question 1

Write the output of the print command in the given table.

a = "Python World"

Print statementOutput
print(a[0]) 
print(a[-2]) 
print(a[5]) 
print(a[7]) 
print(a[-9]) 
print(a[10]) 

Answer

The output of the print commands is given below:

Print statementOutput
print(a[0])P
print(a[-2])l
print(a[5])n
print(a[7])W
print(a[-9])h
print(a[10])l

Explanation:

01234567891011Python World121110987654321\begin{matrix} 0 & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10 & 11 \\ \bold P & \bold y &\bold t &\bold h &\bold o &\bold n & \space &\bold W &\bold o &\bold r &\bold l &\bold d \\ -12 & -11 & -10 & -9 & -8 & -7 & -6 & -5 & -4 & -3 & -2 & -1 \\ \end{matrix}

Activity 15.2

Question 1

Create your portfolio, which should include your name, parent's name, class and address using strings in Python.

Answer

name = "Virat Kohli"
father_name = "Prem Kohli"
mother_name = "Saroj Kohli"
class_name = "Class 10"
address = "New Delhi, India"

print("----- PORTFOLIO -----")
print("Name         :", name)
print("Father's Name:", father_name)
print("Mother's Name:", mother_name)
print("Class        :", class_name)
print("Address      :", address)
Output
----- PORTFOLIO -----
Name         : Virat Kohli
Father's Name: Prem Kohli
Mother's Name: Saroj Kohli
Class        : Class 10
Address      : New Delhi, India

Activity 15.3

Question 1

What would be the output of following program?

print("Hello\nWorld!") 
print("Python\tProgramming") 

Answer

Output
Hello
World!
Python	Programming
Explanation

In the given program, the print() function is used to display output on the screen and escape sequences are used inside strings. The escape sequence \n is used to insert a new line in a string, so after printing Hello, the cursor moves to the next line and World! is printed. The escape sequence \t is used to provide space for one tab, therefore a tab space appears between Python and Programming when it is printed.

Activity 15.4

Question 1

What would be the output of following program?

str2 = "My classmate is Aayan"
if str2.endswith("Aayan"): 
    print("Aayan is studying in class X") 
else: 
    print("Aayan is not the student of class X")

Answer

Output
Aayan is studying in class X
Explanation

The endswith() function returns True if the string ends with a particular suffix. Since the string "My classmate is Aayan" ends with "Aayan", the condition becomes true and the first print() statement is executed.

Activity 15.5

Question 1

What should be the output of following program?

information = "My favorite subject is Python, I want to develop an AI application in Python"
val = information.find('T')
print(val)
if val > 1:
    print("Python is a good programming language for AI applications ")
else:
    print("My favorite subject is Python")

Answer

Output
-1
My favorite subject is Python
Explanation

The find() function returns the index of the first occurrence of the specified value and returns −1 if the value is not found. Since the character 'T' (capital T) is not present in the given string, val becomes -1. As -1 is not greater than 1, the condition in the if statement is false, so the else part is executed.

State True or False

Question 1

Only single quotes can be used to declare a string in Python.

Answer

False

Reason — In Python, a string can be enclosed in single quotes or double quotes.

Question 2

Blank spaces are counted as character in string.

Answer

True

Reason — In a string, each character has a unique index value, and this includes blank spaces, so blank spaces are counted as characters in a string.

Question 3

Special characters cannot be used in strings.

Answer

False

Reason — A string may consist of letters, digits, or symbols, therefore special characters can be used in strings.

Question 4

Backslash (\) is an escape character.

Answer

True

Reason — To insert characters that are not allowed in a string, an escape character is used, and backslash (\) is considered as the escape character.

Question 5

The operator * is also called as replication operator in string.

Answer

True

Reason — In Python, the * operator is used to repeat a string for a specified number of times, therefore it is called the replication operator in strings.

Question 6

Triple quotes are used to create multiline strings.

Answer

True

Reason — In Python triple quotes are used to declare a multiline string.

Question 7

String in Python does not allow membership operator.

Answer

False

Reason — String in Python allows membership operators in and not in.

Question 8

The escape sequence \t is used to produce a blank space.

Answer

False

Reason — The escape sequence \t is used to provide space for one tab, not to produce a blank space.

Question 9

String slicing means to create a sub string.

Answer

True

Reason — String slicing is used to create a sub string from a string.

Question 10

The tolower() method is used to convert all letters of a string into small letters.

Answer

False

Reason — The lower() method is used to convert all the characters of a string from uppercase to lowercase.

Select the correct option

Question 1

The operator used to join two or more strings is ............... .

  1. +
  2. -
  3. *
  4. None of these

Answer

+

Reason — The concatenation operator + is used for joining multiple strings.

Question 2

The method used to convert all characters of a string in upper case is ............... .

  1. toupper()
  2. upper()
  3. capital()
  4. case()

Answer

upper()

Reason — The upper() function converts all the characters of the input string into uppercase.

Question 3

The method used to count the number of characters in a string is ............... .

  1. length()
  2. len()
  3. count()
  4. None of these

Answer

len()

Reasonlen() returns the total number of characters in a string (including spaces).

Question 4

The method used to check that string contains all lower case letter is ............... .

  1. lower()
  2. small()
  3. issmall()
  4. islower()

Answer

islower()

Reason — The islower() function returns True if the string is in lower case.

Question 5

What would be the output of following code ............... .

str1 = "Hello India"
s1 = str1[1:3]
print(s1) 
  1. He
  2. el
  3. Hlo
  4. None of these

Answer

el

Reason — In Python, string indexing starts from 0. The slice operator [1:3] returns the characters from index 1 up to index 2 (end index is excluded), therefore the output is el.

Question 6

What would be the output of following code?

Q1 = "Hello How are you"
val = Q1.count("H")
print(val)
  1. 1
  2. 3
  3. 2
  4. Error

Answer

2

Reason — The count() function returns the number of occurrences of a character in a string. In the string "Hello How are you", the character "H" appears two times, therefore the output is 2.

Question 7

The method used to check that all characters in a string are alpha numeric is ............... .

  1. isal()
  2. isalnum()
  3. isnum()
  4. isalphanum()

Answer

isalnum()

Reason — The isalnum() function returns True if all the elements of the string are alphanumeric.

Question 8

What would be the output of following code?

information = "I am studying in class X !"
val = information.find("studying")
print("The index is: ", val)
  1. 5
  2. 6
  3. 7
  4. Error

Answer

5

Reason — The find() function returns the index of the first occurrence of the specified value. In the given string, the word "studying" starts at index 5, therefore the output is 5.

Fill blanks

Question 1

Fill in the blanks:

  1. """Hello How are you?
    I am good.""" is an example of ................ .
  2. The ................ operator returns true if a character does not belong to a string.
  3. In Python ................ is used to introduce a new line.
  4. The ................ function takes an iterator as an input of argument.
  5. The isdigit() function returns ................ if all the elements in the string are digits.

Answer

  1. """Hello How are you?
    I am good.""" is an example of Multiline string.
  2. The not in operator returns true if a character does not belong to a string.
  3. In Python \n is used to introduce a new line.
  4. The join function takes an iterator as an input of argument.
  5. The isdigit() function returns True if all the elements in the string are digits.

Short answer type questions

Question 1

Write a Python program to convert all the letters of a string in uppercase.

Solution
name = "My name is Jack"
new_name = name.upper()
print(new_name)
Output
MY NAME IS JACK

Question 2

Write a Python program to perform the following tasks.

a. "Hello, my friends, I am Jeck"

b. Replace Jeck with Tiya

Solution
string = "Hello, my friends, I am Jeck"
new_string = string.replace("Jeck", "Tiya")
print(new_string)
Output
Hello, my friends, I am Tiya

Question 3

Write a Python program to check the index of a particular character.

Solution
string = input("Enter a string: ")
ch = input("Enter a character to find its index: ")
val = string.find(ch)
print("The index of the character is:", val)
Output
Enter a string: Python
Enter a character to find its index: t
The index of the character is: 2

Question 4

Write a Python program to create a sub string from a string.

Solution
string = "Knowledge is power"
substring = string[0:9]
print(substring)
Output
Knowledge

Question 5

Write a Python program to demonstrate the use of the join function.

Solution
list1 = ["Riya", "Akshat", "Gem"]
new_string = ",".join(list1)
print(new_string)
Output
Riya,Akshat,Gem

Long answer type questions

Question 1

Explain any four string operators.

Answer

The following are some string operators:

1. Replication operator (*) — The replication operator in Python is used to repeat a string for a specified number of times.

Example:

s1 = "Hello"
print(s1 * 4)

Output: HelloHelloHelloHello

2. Concatenation operator (+) — The concatenation operator (+) is used for joining multiple strings.

Example:

print("Hello" + " Hi")

Output: Hello Hi

3. Membership operator (in) — The membership operator returns true if a character exists in the given string.

Example:

if 't' in "Mountain":
    print("t is present in mountain")

Output: t is present in mountain

4. Membership operator (not in) — This operator returns true if a character does not exist in the given string.

Example:

if 'k' not in "Mountain":
    print("k is not present in mountain")

Output: k is not present in mountain

Question 2

Write a Python program to check that a given string contains only alpha numeric characters. If user is not entering alphanumeric characters prompt him or her to enter it again.

Solution
string1 = input("Enter a string: ")
while True:
    if string1.isalnum():
        print("The given string contains only alphanumeric characters")
        break
    else:
        print("Please enter only alphanumeric characters")
        string1 = input("Enter the string again: ")
Output
Enter a string: Python@123
Please enter only alphanumeric characters
Enter the string again: Python123
The given string contains only alphanumeric characters

Question 3

Write a Python program for the following task:

Take a string entered by the user and check if it begins with the letter "a" or not. If it begins with "a", the user is prompted that it is the first name on the list. If it does not begin with "a", the user is prompted that the string does not begin with the letter "a".

Solution
string1 = input("Enter a string: ")
if string1.startswith("a"):
    print("It is the first name on the list")
else:
    print("The string does not begin with the letter a")
Output
Enter a string: apple
It is the first name on the list

Enter a string: mango
The string does not begin with the letter a

Question 4

Write a Python program to check that a given string is a palindrome or not.

Solution
string1 = input("Enter a string: ")
rev = string1[::-1]

if string1 == rev:
    print("The given string is a palindrome")
else:
    print("The given string is not a palindrome")
Output
Enter a string: madam
The given string is a palindrome

Enter a string: computer
The given string is not a palindrome

Question 5

Write a Python program to reverse a string.

Solution
string1 = input("Enter a string: ")
rev = string1[::-1]
print("Reversed string is:", rev)
Output
Enter a string: education
Reversed string is: noitacude

Higher Order Thinking Skills (HOTS)

Question 1

Take a string and create a substring that contains all the unique characters from the list.

Solution
string1 = input("Enter a string: ")
unique = ""

for ch in string1:
    if ch not in unique:
        unique = unique + ch

print("Substring with unique characters:", unique)
Output
Enter a string: programming
Substring with unique characters: progamin

Question 2

Write a function to check the complexity of a password string. A strong password should contain at least 8 characters, including uppercase letters, lowercase letters and digits.

Solution
def check_password_complexity(password):
    if len(password) < 8:
        return "Weak Password"

    has_upper = False
    has_lower = False
    has_digit = False

    for ch in password:
        if ch.isupper():
            has_upper = True
        elif ch.islower():
            has_lower = True
        elif ch.isdigit():
            has_digit = True

    if has_upper and has_lower and has_digit:
        return "Strong Password"
    else:
        return "Weak Password"

password = input("Enter a password: ")
result = check_password_complexity(password)
print(result)
Output
Enter a password: Abc12345
Strong Password
PrevNext