Strings in Python

ICSE Class 10 Robotics & AI · KIPS Robotics & AI · 36 solved questions

Exercise
1Activity 15.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]) 
Show SolutionHide Solution↓

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:

$$\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}$$

1Activity 15.2

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

Show SolutionHide Solution↓
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)
----- PORTFOLIO -----
Name         : Virat Kohli
Father's Name: Prem Kohli
Mother's Name: Saroj Kohli
Class        : Class 10
Address      : New Delhi, India
1Activity 15.3

What would be the output of following program?

print("Hello\nWorld!") 
print("Python\tProgramming") 
Show SolutionHide Solution↓
Hello
World!
Python	Programming

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.

1Activity 15.4

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")
Show SolutionHide Solution↓
Aayan is studying in class X

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.

1Activity 15.5

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")
Show SolutionHide Solution↓
-1
My favorite subject is Python

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.

1State True or False

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

Show SolutionHide Solution↓

False

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

2State True or False

Blank spaces are counted as character in string.

Show SolutionHide Solution↓

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.

3State True or False

Special characters cannot be used in strings.

Show SolutionHide Solution↓

False

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

4State True or False

Backslash (\) is an escape character.

Show SolutionHide Solution↓

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.

5State True or False

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

Show SolutionHide Solution↓

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.

6State True or False

Triple quotes are used to create multiline strings.

Show SolutionHide Solution↓

True

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

7State True or False

String in Python does not allow membership operator.

Show SolutionHide Solution↓

False

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

8State True or False

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

Show SolutionHide Solution↓

False

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

9State True or False

String slicing means to create a sub string.

Show SolutionHide Solution↓

True

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

10State True or False

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

Show SolutionHide Solution↓

False

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

1Select the correct option

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

Show SolutionHide Solution↓

+

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

2Select the correct option

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

Show SolutionHide Solution↓

upper()

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

3Select the correct option

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

Show SolutionHide Solution↓

len()

Reason — len() returns the total number of characters in a string (including spaces).

4Select the correct option

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

Show SolutionHide Solution↓

islower()

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

5Select the correct option

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

str1 = "Hello India"
s1 = str1[1:3]
print(s1) 
Show SolutionHide Solution↓

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.

6Select the correct option

What would be the output of following code?

Q1 = "Hello How are you"
val = Q1.count("H")
print(val)
Show SolutionHide Solution↓

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.

7Select the correct option

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

Show SolutionHide Solution↓

isalnum()

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

8Select the correct option

What would be the output of following code?

information = "I am studying in class X !"
val = information.find("studying")
print("The index is: ", val)
Show SolutionHide Solution↓

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.

1Fill blanks

Fill in the blanks:

Show SolutionHide Solution↓
  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.
1Short answer type questions

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

Show SolutionHide Solution↓
name = "My name is Jack"
new_name = name.upper()
print(new_name)
MY NAME IS JACK
2Short answer type questions

Write a Python program to perform the following tasks.

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

b. Replace Jeck with Tiya

Show SolutionHide Solution↓
string = "Hello, my friends, I am Jeck"
new_string = string.replace("Jeck", "Tiya")
print(new_string)
Hello, my friends, I am Tiya
3Short answer type questions

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

Show SolutionHide 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)
Enter a string: Python
Enter a character to find its index: t
The index of the character is: 2
4Short answer type questions

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

Show SolutionHide Solution↓
string = "Knowledge is power"
substring = string[0:9]
print(substring)
Knowledge
5Short answer type questions

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

Show SolutionHide Solution↓
list1 = ["Riya", "Akshat", "Gem"]
new_string = ",".join(list1)
print(new_string)
Riya,Akshat,Gem
1Long answer type questions

Explain any four string operators.

Show SolutionHide Solution↓

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

2Long answer type questions

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.

Show SolutionHide 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: ")
Enter a string: Python@123
Please enter only alphanumeric characters
Enter the string again: Python123
The given string contains only alphanumeric characters
3Long answer type questions

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".

Show SolutionHide 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")
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
4Long answer type questions

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

Show SolutionHide 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")
Enter a string: madam
The given string is a palindrome

Enter a string: computer
The given string is not a palindrome
5Long answer type questions

Write a Python program to reverse a string.

Show SolutionHide Solution↓
string1 = input("Enter a string: ")
rev = string1[::-1]
print("Reversed string is:", rev)
Enter a string: education
Reversed string is: noitacude
1Higher Order Thinking Skills (HOTS)

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

Show SolutionHide 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)
Enter a string: programming
Substring with unique characters: progamin
2Higher Order Thinking Skills (HOTS)

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.

Show SolutionHide 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)
Enter a password: Abc12345
Strong Password

Press ↓ to reveal a solution and move to the next question. Back to KIPS Robotics & AI.

Free sample bank