How are strings internally stored ?
Answer
Strings are a sequence of characters where each character has a unique position (index). The indexes of a string begin from 0 to (length - 1) in the forward direction and from -1, -2, -3,..., -length in the backward direction.
For a string s storing 'Goldy', what would s[0] and s[-1] return ?
Answer
For the string s storing 'Goldy':
s[0]: The index 0 refers to the first character in the string. In this case, the character at index 0 is 'G'.s[-1]: The index -1 refers to the last character in the string. In this case, the last character is 'y'.
The last character of a string s is at index len(s) - 1. True/False.
Answer
True.
The last character of a string s is at the index len(s) - 1 because indexing starts from 0. Therefore, the final character is at the position equal to the length of the string minus 1.
For strings, + means (1); * means (2). Suggest words for positions (1) and (2).
Answer
For strings,
(1) concatenation (+)
(2) repetition (*)
Given that
s1 = "spam"
s2 = "nil"What is the output produced by following expression ?
(a) "The Knights who say," + s2
(b) 3 * s1 + 2 * s2
(c) s1[1]
Answer
(a)
The Knights who say,nil
The above expression concatenates the string "The Knights who say," with the value of s2, which is "nil".
(b)
spamspamspamnilnil
When a string is multiplied by *, it repeats that string the specified number of times. In this case, s1 = "spam" is repeated 3 times, and s2 = "nil" is repeated 2 times. So, 3 * s1 results in "spamspamspam" and 2 * s2 results in "nilnil". These two results are then concatenated using + operator.
(c)
p
The above expression accesses the character at index 1 of the string s1, which is "spam". The character at index 1 is "p".
What are membership operators ? What do they basically do ?
Answer
Membership operators in Python are in and not in. They are used to test whether a value is present in a sequence.
inreturns True if a character or a substring exists in the given string; False otherwise.not inreturns True if a character or a substring does not exist in the given string; False otherwise.
On what principles, the strings are compared in Python ?
Answer
Strings in Python are compared using relational operators (<, <=, >, >=, ==, !=). These comparisons are based on standard character-by-character comparison rules for Unicode, which follow lexicographical order (i.e., dictionary order).
What will be the result of following expressions ?
(a) "WoW Python"[1]
(b) "Strings are fun."[5]
(c) len("awesome")
(d) "Mystery"[:4]
(e) "apple" > "pineapple"
(f) "pineapple" < "Peach"
(g) "cad" in "abracadabra"
(h) "apple" in "Pineapple"
(i) "pine" in "Pineapple"
Answer
(a) "WoW Python"[1]
Output: 'o'
Explanation: The character at index 1 is 'o'.
(b) "Strings are fun."[5]
Output: 'g'
Explanation: The character at index 5 is 'g'.
(c) len("awesome")
Output: 7
Explanation: The string "awesome" has 7 characters.
(d) "Mystery"[:4]
Output: 'Mys'
Explanation: This slices the string from the start up to index 4.
(e) "apple" > "pineapple"
Output: False
Explanation: "apple" is less than "pineapple" in lexicographical order.
(f) "pineapple" < "Peach"
Output: False
Explanation: In lexicographical order, lowercase letters come after uppercase letters, so "pineapple" is considered greater than "Peach".
(g) "cad" in "abracadabra"
Output: True
Explanation: The substring "cad" exists within "abracadabra".
(h) "apple" in "Pineapple"
Output: False
Explanation: The string "apple" (all lowercase) is not found as a substring in "Pineapple" because the first letter of "Pineapple" is uppercase ('P').
(i) "pine" in "Pineapple"
Output: False
Explanation: The lowercase "pine" does not match the uppercase "P" in "Pineapple".
What do you understand by string slices ?
Answer
In Python, the term 'string slice' refers to a specific part of a string obtained by using a range of indices.
Considering the same strings s1 and s2 of question 5 above, evaluate the following expressions:
(a) s1[1:3]
(b) s1[2] + s2[:2]
(c) s1 + s2[-1]
(d) s1[:3] + s1[3:]
(e) s2[:-1] + s2[-1:]
Answer
The strings s1 and s2 are as follows:
s1 = "spam"
s2 = "nil"(a) s1[1:3]
pa
The above expresions slices the string s1 from index 1 to index 2. It results in "pa".
(b) s1[2] + s2[:2]
ani
s1[2]gives the character at index 2 ofs1, which is "a".s2[:2]slices the strings2from the index 0 to 1, which is "ni".- Concatenating these gives "a" + "ni" = "ani".
(c) s1 + s2[-1]
"spaml"
s2[-1]gives the last character ofs2, which is "l".- Concatenating
s1and "l" results in "spaml".
(d) s1[:3] + s1[3:]
"spam"
s1[:3]slices the string from the index 0 to 2, which is "spa".s1[3:]slices from index 3 to the end, which is "m".- Concatenating these results in "spa" + "m" = "spam".
(e) s2[:-1] + s2[-1:]
"nil"
s2[:-1]slices the string from the index 0 to the second last character, which is "ni".s2[-1:]slices the last character, which is "l".- Concatenating these results in "ni" + "l" = "nil".
What is the role of these functions ?
(i) isalpha()
(ii) isalnum()
(iii) isdigit()
(iv) isspace()
Answer
(i) isalpha() — It returns True if all characters in the string are alphabetic and there is at least one character, False otherwise.
(ii) isalnum() — It returns True if the characters in the string are alphanumeric (alphabets or numbers) and there is at least one character, False otherwise.
(iii) isdigit() — It returns True if all the characters in the string are digits. There must be at least one character, otherwise it returns False.
(iv) isspace() — It returns True if there are only whitespace characters in the string. There must be at least one character. It returns False otherwise.
Name the case related string manipulation functions.
Answer
The case related string manipulation functions are as follows:
- capitalize()
- islower()
- isupper()
- lower()
- upper()
- title()
- istitle()
How is islower() function different from lower() function ?
Answer
The islower() function returns True if all cased characters in the string are lowercase, and there must be at least one cased character. It returns False otherwise. The lower() function, on the other hand, returns a copy of the string converted to lowercase.
What is the utility of find() function ?
Answer
The find() function returns the lowest index in the string where the substring sub is found within the slice range of start and end. Returns -1 if sub is not found.
How is capitalize() function different from upper() function ?
Answer
The capitalize() function returns a copy of the string with its first character capitalized, while the upper() function returns a copy of the string converted to uppercase.
Negative index -1 belongs to .......... of string.
- first character
- last character
- second last character
- second character
Answer
last character
Reason — In Python, negative indexing allows to access elements from the end of a sequence. Specifically, an index of -1 refers to the last character of the string.
Which of the following is/are not legal string operators?
- in
- +
- *
- /
Answer
/
Reason — In Python, the '/' operator is not a legal string operator. The valid operators for strings include:
in— used to check if a substring exists within a string.+— used for concatenating two strings.*— used to repeat a string a specified number of times.
Which of the following functions will return the total number of characters in a string?
- count()
- index()
- len()
- all of these
Answer
len()
Reason — The len() function returns the length of its argument string, i.e., it returns the count of characters in the passed string.
Which of the following functions will return the last three characters of a string s ?
- s[3:]
- s[:3]
- s[-3:]
- s[:-3]
Answer
s[-3:]
Reason — The expression s[-3:] returns the last three characters of the string s. Negative indices count from the end of the string, so -1 is the last character, -2 is the second last, and -3 is the third last.
Which of the following functions will return the first three characters of a string s?
- s[3:]
- s[:3]
- s[-3:]
- s[:-3]
Answer
s[:3]
Reason — The expression s[:3] returns a substring starting from the beginning of the string up to the character at index 3. Therefore, it returns the first three characters of the string s.
Which of the following functions will return the string in all caps?
- upper()
- toupper()
- isupper()
- to-upper()
Answer
upper()
Reason — The upper() function returns a copy of the string converted to uppercase.
Which of the following functions will return the string with every 'P' replaced with a 'z'?
- find()
- index()
- replace()
- split()
Answer
replace()
Reason — The replace() function returns a copy of the string with all occurrences of a specified substring (in this case, 'P') is replaced with another substring (here, 'z').
Which of the following functions will return a list containing all words of the string?
- find()
- index()
- partition()
- split()
Answer
split()
Reason — The split() function splits a string based on given string or character and returns a list containing split strings as members.
Which of the following functions will always return a tuple of 3 elements?
- find()
- index()
- partition()
- split()
Answer
partition()
Reason — The partition() method splits the string at the first occurrence of separator, and returns a tuple containing three items: the part before the separator, the separator itself and the part after the separator.
What is the output of the following code?
str1 = "Mission 999"
str2 = "999"
print(str1.isdigit(),str2.isdigit())- False True
- False False
- True False
- True True
Answer
False True
Reason — The isdigit() method checks if all characters in a string are digits. In this case, str1 contains non-digit characters ("Mission"), so str1.isdigit() returns False. However, str2 contains only digits ("999"), so str2.isdigit() returns True. Thus, the output is False True.
Choose the correct function to get the ASCII code of a character.
- char('char')
- ord('char')
- ascii('char')
- All of these
Answer
ord('char')
Reason — The ord() function in Python takes a single character (a string of length 1) and returns its corresponding ASCII (or Unicode) code.
Which method should I use to convert String "Python programming is fun" to "Python Programming Is Fun" ?
- capitalize()
- title()
- istitle()
- upper()
Answer
title()
Reason — The title() method converts the first character of each word in a string to uppercase and the rest to lowercase, resulting in "Python Programming Is Fun".
Guess the correct output of the following String operations.
str1 = 'Wah'
print(str1*2)- WahWah
- TypeError: unsupported operand type(s) for * : 'str' and 'int'
- WWaahh
- Wah2
Answer
WahWah
Reason — The * operator in Python, when used with strings, performs repetition. For instance, str1 * 2 concatenates the string str1 with itself two times, resulting in "WahWah".
What is the output of the following string operation?
str = "My roll no. is 12"
print(str.isalnum())- True
- False
- Error
- No output
Answer
False
Reason — The isalnum() method checks if all characters in the string are alphanumeric (letters or numbers) and there are no spaces or special characters. In this case, the string "My roll no. is 12" contains spaces and dot, so it returns False.
Select the correct output of the following String operations.
str1 = 'Waha'
print(str1[:3] + 'Bhyi' + str1[-3:])- Wah Bhyi Wah
- WahBhyiaha
- WahBhyiWah
- WahBhyiWaha
Answer
WahBhyiaha
Reason — The expression str1[:3] returns the substring from the start of the string up to index 3, which gives "Wah". The expression str1[-3:] returns the substring starting from the third last character to the end of the string, resulting in "aha". The final print statement concatenates these two substrings with the string 'Bhyi', resulting in "Wah" + "Bhyi" + "aha", which produces the output "WahBhyiaha".
Select the correct output of the following String operations.
str = "my name is Anu John"
print(str.capitalize())- 'My name is anu john'
- TypeError: unsupported operand type(s) for * : 'str' and 'int'
- 'My name is Anu John'
- 'My Name Is Anu John'
Answer
'My name is anu john'
Reason — The capitalize() method returns a copy of the string with the first character capitalized and all other characters in lowercase. Therefore, in the string "my name is Anu John", the first character 'm' becomes 'M', and the rest of the string is converted to lowercase, resulting in 'My name is anu john'.
Choose the correct function to get the character from ASCII number.
- ascii(number)
- char(number)
- chr(number)
- all of these
Answer
chr(number)
Reason — The chr() function in Python takes an ASCII number as an argument and returns the corresponding character.
s = ' '(single space). Then s.isalnum() will return.
- True
- False
- Error
- nothing
Answer
False
Reason — The isalnum() method checks if all characters in the string are alphanumeric (letters or digits). Since a single space is neither a letter nor a digit, s.isalnum() will return False.
Which of the following functions removes all leading and trailing spaces from a string?
- lstrip()
- rstrip()
- strip()
- all of these
Answer
strip()
Reason — The strip() functions returns a copy of the string with leading and trailing whitespaces removes, i.e., whitespaces from the leftmost and the rightmost ends are removed.
Which of the following functions will raise an error if the given substring is not found in the string?
- find()
- index()
- replace()
- all of these
Answer
index()
Reason — The index() function returns the lowest index where the specified substring is found. If the substring is not found then an exception, ValueError, is raised.
The string indexes begin 0 onwards.
For strings, + operator performs concatenation.
For strings, * operator performs replication.
The in and not in are membership operators for strings (in, not in).
The ord() returns the ASCII value of a given character.
If a string contains letters and digits, function isalnum() will return true.
'ab'.isalpha() will return value as True.
To get each word's first letter capitalized, title() function is used.
Function index() raises an exception if the substring is not found.
Function split() divides a line of text into individual words.
Strings have both positive and negative indexes.
Answer
True
Reason — In Python, strings can be indexed using both positive and negative integers. Positive indexes start from 0 for the first character, while negative indexes count from the end, with -1 representing the last character.
Python does not support a character type; a single character is treated as strings of length one.
Answer
True
Reason — Python does not have a separate character type. Instead, a single character is treated as a string with a length of one. This allows to use all string operations and methods on single characters just like we would with longer strings.
Strings are immutable in Python, which means a string cannot be modified.
Answer
True
Reason — In Python, strings are immutable, meaning that once a string is created, its contents cannot be changed.
Like '+', all other arithmetic operators are also supported by strings.
Answer
False
Reason — In Python, the + operator is used to concatenate strings, but other arithmetic operators such as - and / are not supported for strings. Attempting to use these operators with strings will result in a TypeError. Only concatenation using + and repetition using * are valid operations for strings.
Functions capitalize() and title() return the same result.
Answer
False
Reason — The capitalize() method returns a copy of the string with only the first character capitalized and all other characters converted to lowercase. In contrast, the title() method capitalizes the first character of each word in the string while converting all other characters to lowercase.
Functions partition() and split() work identically.
Answer
False
Reason — The partition() method splits the string at the first occurrence of the specified separator and returns a tuple containing three parts: the substring before the separator, the separator itself, and the substring after the separator. In contrast, the split() function splits a string based on given string or character and returns a list containing split strings as members.
The find() and index() are similar functions.
Answer
True
Reason — The find() and index() functions are similar because both functions return the lowest index in the string where the substring sub is found within the slice range of start and end.
The find() does not raise an exception if the substring is not found.
Answer
True
Reason — The find() function returns the lowest index in the string where the substring sub is found within the slice range of start and end. Returns -1 if sub is not found.
If the substring is not found then an exception, ValueError, is raised.
The partition() function's result is always a 3-element tuple.
Answer
True
Reason — The partition() method splits the string at the first occurrence of separator, and returns a tuple containing three items: the part before the separator, the separator itself and the part after the separator.
The split() returns always a 3-element list.
Answer
False
Reason — The split() function splits a string based on given string or character and returns a list containing split strings as members.
Assertion. The individual characters of a string are randomly stored in memory.
Reason. Python strings are stored in memory by storing individual characters in contiguous memory locations.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
A is false but R is true.
Explanation
Individual characters of a string are not randomly stored; they follow a specific order based on the sequence of the string. Python strings are stored in memory with individual characters in contiguous memory locations, maintaining the order in which they appear.
Assertion. The position and index of string characters are different.
Reason. The positions for strings's characters vary from 1...n, where n is the size of the string. The indices for string's characters vary from 0 to n-1.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
The position and index of string characters are different. Character positions are numbered from 1 to n (where n is the length of the string), while indices are numbered from 0 to n-1. This means that the first character of a string is at position 1 but at index 0, and the second character is at position 2 but at index 1, and so forth. For example, in the string "Python," the character 'P' is at position 1 but has an index of 0.
Assertion. Operators + and * can work with numbers as well as strings.
Reason. Unlike numbers, for strings, + means concatenation and * means replication.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
The operators + and * can be applied to both numbers and strings in Python. For numbers, + performs addition, while * performs multiplication. However, for strings, + is used for concatenation (combining two strings), and * is used for replication (repeating a string a specified number of times).
Assertion. Like numbers, ==, >, < can also compare two strings.
Reason. Comparison of Python strings takes place in dictionary order by applying character-by-character comparison rules for ASCII/Unicode.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
Python allows the comparison of strings using operators such as ==, >, and <. For instance, == checks for equality between two strings, while > and < compare strings based on their lexicographical order. String comparison in Python is determined by the ASCII or Unicode values of the characters, meaning that the comparison is performed character by character according to their respective values.
Assertion. String slices and substrings, both are extracted subparts of a string.
Reason. String slices and substrings mean the same.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
A is true but R is false.
Explanation
Both string slices and substrings are extracted subparts of a string. A string slice refers to a specific portion of a string extracted using slicing syntax (e.g., str[start:end]), whereas a substring is any sequence of characters within a string that may or may not be obtained through slicing. Therefore, string slices and substrings do not mean the same.
Assertion. String slices and substrings, despite being subparts of a string, are not the same.
Reason. While the substring contains a continuous subpart of the string, the slices may or may not contain continuous subparts of a string.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
Both A and R are true and R is the correct explanation of A.
Explanation
Both string slices and substrings are extracted subparts of a string, but they do not mean the same. A string slice refers to a specific portion of a string extracted using slicing syntax (e.g., str[start:end]), whereas a substring is any sequence of characters within a string that may or may not be obtained through slicing.
Assertion. A string slice contains a part of the strings as per s[start:end:n], starting at start, containing every nth character, extending upto end, not including character at end.
Reason. A substring contains contiguous characters unlike string slices.
- Both A and R are true and R is the correct explanation of A.
- Both A and R are true but R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.
- Both A and R are false or not fully true.
Answer
Both A and R are true but R is not the correct explanation of A.
Explanation
A string slice is defined by the syntax s[start:end:n], which specifies a portion of the string starting at the index start, including every nth character, and extending up to (but not including) the character at the index end. In contrast, a substring contains contiguous characters unlike string slices.
Write a Python script that traverses through an input string and prints its characters in different lines — two characters per line.
Answer
str = input("Enter the string: ")
length = len(str)
for a in range(0, length, 2):
print(str[a:a+2])Output
Enter the string: KnowledgeBoat
Kn
ow
le
dg
eB
oa
t
Out of the following operators, which ones can be used with strings in Python?
=, -, *, /, //, %, >, <>, in, not in, <=
Answer
The following Python operators can be used with strings:
=, *, >, in, not in, <=
What is the result of following statement, if the input is 'Fun'?
print(input("...") + "trial" + "Ooty" * 3)
Answer
The result of the statement is:
FuntrialOotyOotyOoty
Which of the following is not a Python legal string operation?
(a) 'abc' + 'abc'
(b) 'abc' * 3
(c) 'abc' + .3
(d) 'abc.lower()
Answer
'abc' + .3 is not a legal string operation in Python. The operands of + operator should be both string or both numeric. Here one operand is string and other is numeric. This is not allowed in Python.
Can you say strings are character lists? Why? Why not?
Answer
Strings are sequence of characters where each character has a unique index. This implies that strings are iterable like lists but unlike lists they are immutable so they cannot be modified at runtime. Therefore, strings can't be considered as character lists. For example,
str = 'cat'
# The below statement
# is INVALID as strings
# are immutable
str[0] = 'b'
# Considering character lists
strList = ['c', 'a', 't']
# The below statement
# is VALID as lists
# are mutable
strList[0] = 'b'Given a string S = "CARPE DIEM". If n is length/2 (length is the length of the given string), then what would following return?
(a) S[: n]
(b) S[n :]
(c) S[n : n]
(d) S[1 : n]
(e) S[n : length - 1]
Answer
(a) CARPE
(b) DIEM
(c) (Empty String)
(d) ARPE
(e) DIE
From the string S = "CARPE DIEM", which ranges return "DIE" and "CAR"?
Answer
- S[6:9] returns DIE
- S[:3] returns CAR
What happens when from a string slice you skip the start and/or end values of the slice?
Answer
If start value is skipped, it is assumed as 0 i.e. the slice begins from the start of the string.
If end value is skipped, it is assumed as the last index of the string i.e. the slice extends till the end of the string.
What would the following expressions return?
- "Hello World".upper( ).lower( )
- "Hello World".lower( ).upper( )
- "Hello World".find("Wor", 1, 6)
- "Hello World".find("Wor")
- "Hello World".find("wor")
- "Hello World".isalpha( )
- "Hello World".isalnum( )
- "1234".isdigit( )
- "123FGH".isdigit( )
Answer
- hello world
- HELLO WORLD
- -1
- 6
- -1
- False
- False
- True
- False
Explanation
- upper() first converts all letters of "Hello World" to uppercase. Then "HELLO WORLD".lower() converts all letters to lowercase.
- lower() first converts all letters of "Hello World" to lowercase. Then "hello world".upper() converts all letters to uppercase.
- "Hello World".find("Wor", 1, 6) searches for the presence of substring "Wor" between 1 and 6 indexes of string "Hello World". Substring from 1 to 6 index is "ello W". As "Wor" is not present in this hence the result is False.
- "Hello World".find("Wor") searches for the presence of substring "Wor" in the entire "Hello World" string. Substring "Wor" starts at index 6 of "Hello World" hence the result is 6.
- "Hello World".find("wor") searches for the presence of substring "wor" in the entire "Hello World" string. find() performs case sensitive search so "wor" and "Wor" are different hence the result is -1.
- "Hello World".isalpha( ) checks if all characters in the string as alphabets. As a space is also present in the string hence it returns False.
- "Hello World".isalnum( ) checks if all characters in the string are either alphabets or digits. As a space is also present in the string which is neither an alphabet nor a string hence it returns False.
- "1234".isdigit( ) checks if all characters in the string are digits or not. As all characters are digits hence the result is True.
- As "FGH" in the string "123FGH" are not digits hence the result is False.
Which functions would you choose to use to remove leading and trailing white spaces from a given string?
Answer
lstrip() removes leading white-spaces, rstrip() removes trailing white-spaces and strip() removes leading and trailing white-spaces from a given string.
Try to find out if for any case, the string functions isalnum( ) and isalpha( ) return the same result
Answer
isalnum( ) and isalpha( ) return the same result in the following cases:
- If string contains only alphabets then both isalnum( ) and isalpha( ) return True. For example, "Hello".isalpha() and "Hello".isalnum() return True.
- If string contains only special characters and/or white-spaces then both isalnum( ) and isalpha( ) return False. For example, "*#".isalpha() and "*#".isalnum() return False.
Suggest appropriate functions for the following tasks:
- To check whether the string contains digits
- To find for the occurrence a string within another string
- To convert the first letter of a string to upper case
- to capitalize all the letters of the string
- to check whether all letters of the string are in capital letters
- to remove from right of a string all string-combinations from a given set of letters
- to remove all white spaces from the beginning of a string
Answer
- isdigit()
- find()
- capitalize()
- upper()
- isupper()
- rstrip(characters)
- lstrip()
In a string slice, the start and end values can be beyond limits. Why?
Answer
String slicing always returns a subsequence and empty subsequence is a valid sequence. Thus, when a string is sliced outside the bounds, it still can return empty subsequence and hence Python gives no errors and returns empty subsequence.
Can you specify an out of bound index when accessing a single character from a string? Why?
Answer
We cannot specify an out of bound index when accessing a single character from a string, it will cause an error. When we use an index, we are accessing a constituent character of the string. If the index is out of bounds there is no character to return from the given index hence Python throws string index out of range error.
Can you add two strings? What effect does ' + ' have on strings?
Answer
Yes two strings can be added using the '+' operator. '+' operator concatenates two strings.
What is the result of the following expression?
print("""
1
2
3
""")Answer
1
2
3
What is the result of the following expression?
text = "Test.\nNext line."
print (text)Answer
Test.
Next line.
What is the result of the following expression?
print ('One', ' Two ' * 2)
print ('One ' + 'Two' * 2)
print (len('10123456789'))Answer
One Two Two
One TwoTwo
11
What is the result of the following expression?
s = '0123456789'
print(s[3], ", ", s[0 : 3], " - ", s[2 : 5])
print(s[:3], " - ", s[3:], ", ", s[3:100])
print(s[20:], s[2:1], s[1:1])Answer
3 , 012 - 234
012 - 3456789 , 3456789
What is the result of the following expression?
s ='987654321'
print (s[-1], s[-3])
print (s[-3:], s[:-3])
print (s[-100:-3], s[-100:3])Answer
1 3
321 987654
987654 987
What will be the output produced by following code fragments?
y = str(123)
x = "hello" * 3
print (x, y)
x = "hello" + "world"
y = len(x)
print (y, x)Answer
hellohellohello 123
10 helloworld
str(123) converts the number 123 to string and stores in y so y becomes "123". "hello" * 3 repeats "hello" 3 times and stores it in x so x becomes "hellohellohello".
"hello" + "world" concatenates both the strings so x becomes "helloworld". As "helloworld" contains 10 characters so len(x) returns 10.
What will be the output produced by following code fragments?
x = "hello" + \
"to Python" + \
"world"
for char in x :
y = char
print (y, ' : ', end = ' ')Answer
h : e : l : l : o : t : o : : P : y : t : h : o : n : w : o : r : l : d :
Inside the for loop, we are traversing the string "helloto Pythonworld" character by character and printing each character followed by a colon (:).
What will be the output produced by following code fragments?
x = "hello world"
print (x[:2], x[:-2], x[-2:])
print (x[6], x[2:4])
print (x[2:-3], x[-4:-2])Answer
he hello wor ld
w ll
llo wo or
x[:2] ⇒ he
x[:-2] ⇒ hello wor
x[-2:] ⇒ ld
x[6] ⇒ w
x[2:4] ⇒ ll
x[2:-3] ⇒ llo wo
x[-4:-2] ⇒ or
Carefully go through the code given below and answer the questions based on it :
theStr = " This is a test "
inputStr = input(" Enter integer: ")
inputlnt = int(inputStr)
testStr = theStr
while inputlnt >= 0 :
testStr = testStr[1:-1]
inputlnt = inputlnt - 1
testBool = 't' in testStr
print (theStr) # Line 1
print (testStr) # Line 2
print (inputlnt) # Line 3
print (testBool) # Line 4 (i) Given the input integer 3, what output is produced by Line 1?
- This is a test
- This is a
- is a test
- is a
- None of these
Answer
Option 1 — This is a test
(ii) Given the input integer 3, what output is produced by Line 2?
- This is a test
- s is a t
- is a test
- is a
- None of these
Answer
Option 2 — s is a t
As input is 3 and inside the while loop, inputlnt decreases by 1 in each iteration so the while loop executes 4 times for inputlnt values 3, 2, 1, 0.
1st Iteration
testStr = "This is a test"
2nd Iteration
testStr = "his is a tes"
3rd Iteration
testStr = "is is a te"
4th Iteration
testStr = "s is a t"
(iii) Given the input integer 2, what output is produced by Line 3?
- 0
- 1
- 2
- 3
- None of these
Answer
Option 5 — None of these
Value of inputlnt will be -1 as till inputlnt >= 0 the while loop will continue executing.
(iv) Given the input integer 2, what output is produced by Line 4?
- False
- True
- 0
- 1
- None of these
Answer
Option 2 — True
As input is 2 and inside the while loop, inputlnt decreases by 1 in each iteration so the while loop executes 3 times for inputlnt values 2, 1, 0.
1st Iteration
testStr = "This is a test"
2nd Iteration
testStr = "his is a tes"
3rd Iteration
testStr = "is is a te"
After the while loop finishes executing, value of testStr is "is is a te". 't' in testStr returns True as letter t is present in testStr.
Carefully go through the code given below and answer the questions based on it :
testStr = "abcdefghi"
inputStr = input ("Enter integer:")
inputlnt = int(inputStr)
count = 2
newStr = ''
while count <= inputlnt :
newStr = newStr + testStr[0 : count]
testStr = testStr[2:] #Line 1
count = count + 1
print (newStr) # Line 2
print (testStr) # Line 3
print (count) # Line 4
print (inputlnt) # Line 5 (i) Given the input integer 4, what output is produced by Line 2?
- abcdefg
- aabbccddeeffgg
- abcdeefgh
- ghi
- None of these
Answer
Option 3 — abcdeefgh
Input integer is 4 so while loop will execute 3 times for values of count as 2, 3, 4.
1st Iteration
newStr = newStr + testStr[0:2]
⇒ newStr = '' + ab
⇒ newStr = ab
testStr = testStr[2:]
⇒ testStr = cdefghi
2nd Iteration
newStr = newStr + testStr[0:3]
⇒ newStr = ab + cde
⇒ newStr = abcde
testStr = testStr[2:]
⇒ testStr = efghi
3rd Iteration
newStr = newStr + testStr[0:4]
⇒ newStr = abcde + efgh
⇒ newStr = abcdeefgh
testStr = testStr[2:]
⇒ testStr = ghi
(ii) Given the input integer 4, what output is produced by Line 3?
- abcdefg
- aabbccddeeffgg
- abcdeefgh
- ghi
- None of these
Answer
Option 4 — ghi
Input integer is 4 so while loop will execute 3 times for values of count as 2, 3, 4.
1st Iteration
testStr = testStr[2:]
⇒ testStr = cdefghi
2nd Iteration
testStr = testStr[2:]
⇒ testStr = efghi
3rd Iteration
testStr = testStr[2:]
⇒ testStr = ghi
(iii) Given the input integer 3, what output is produced by Line 4?
- 0
- 1
- 2
- 3
- None of these
Answer
Option 5 — None of these
Looking at the condition of while loop — while count <= inputlnt, the while loop will stop executing when count becomes greater than inputlnt. Value of inputlnt is 3 so when loop stops executing count will be 4.
(iv) Given the input integer 3, what output is produced by Line 5?
- 0
- 1
- 2
- 3
- None of these
Answer
Option 4 — 3
The input is converted from string to integer and after that its value is unchanged in the code so line 5 prints the input integer 3.
(v) Which statement is equivalent to the statement found in Line 1?
- testStr = testStr[2:0]
- testStr = testStr[2:-1]
- testStr = testStr[2:-2]
- testStr = testStr - 2
- None of these
Answer
Option 5 — None of these
Carefully go through the code given below and answer the questions based on it :
inputStr = input(" Give me a string:")
biglnt = 0
littlelnt = 0
otherlnt = 0
for ele in inputStr:
if ele >= 'a' and ele <= 'm': # Line 1
littlelnt = littlelnt + 1
elif ele > 'm' and ele <= 'z':
biglnt = biglnt + 1
else:
otherlnt = otherlnt + 1
print (biglnt) # Line 2
print (littlelnt) # Line 3
print (otherlnt) # Line 4
print (inputStr.isdigit()) # Line 5(i) Given the input abcd what output is produced by Line 2?
- 0
- 1
- 2
- 3
- 4
Answer
Option 1 — 0
In the input abcd, all the letters are between a and m so the condition — if ele >= 'a' and ele <= 'm' is always true. Hence, biglnt is 0.
(ii) Given the input Hi Mom what output is produced by Line 3?
- 0
- 1
- 2
- 3
- None of these
Answer
Option 3 — 2
In the input Hi Mom, only two letters i and m satisfy the condition — if ele >= 'a' and ele <= 'm'. Hence, value of littlelnt is 2.
(iii) Given the input Hi Mom what output is produced by Line 4?
- 0
- 1
- 2
- 3
- None of these
Answer
Option 4 — 3
In the input Hi Mom, 3 characters H, M and space are not between a and z. So for these 3 characters the statement in else part — otherlnt = otherlnt + 1 is executed. Hence, value of otherlnt is 3.
(iv) Given the input 1+2 =3 what output is produced by Line 5?
- 0
- 1
- True
- False
- None of these
Answer
Option 4 — False
As all characters in the input string 1+2 =3 are not digits hence isdigit() returns False.
(v) Give the input Hi Mom, what changes result from modifying Line 1 from
if ele >= 'a' and ele <='m' to the expression
if ele >= 'a' and ele < 'm'?
- No change
- otherlnt would be larger
- littlelnt would be larger
- biglnt would be larger
- None of these
Answer
Option 2 — otherlnt would be larger
For letter m, now else case will be executed increasing the value of otherlnt.
Carefully go through the code given below and answer the questions based on it :
in1Str = input(" Enter string of digits: ")
in2Str = input(" Enter string of digits: ")
if len(in1Str)>len(in2Str):
small = in2Str
large = in1Str
else:
small = in1Str
large = in2Str
newStr = ''
for element in small:
result = int(element) + int(large[0])
newStr = newStr + str(result)
large = large[1:]
print (len(newStr)) # Line 1
print (newStr) # Line 2
print (large) # Line 3
print (small) # Line 4(i) Given a first input of 12345 and a second input of 246, what result is produced by Line 1?
- 1
- 3
- 5
- 0
- None of these
Answer
Option 2 — 3
As length of smaller input is 3, for loop executes 3 times so 3 characters are added to newStr. Hence, length of newStr is 3.
(ii) Given a first input of 12345 and a second input of 246, what result is produced by Line 2?
- 369
- 246
- 234
- 345
- None of these
Answer
Option 1 — 369
For loop executes 3 times as length of smaller input is 3.
1st Iteration
result = 2 + 1
⇒ result = 3
newStr = '' + '3'
⇒ newStr = '3'
large = 2345
2nd Iteration
result = 4 + 2
⇒ result = 6
newStr = '3' + '6'
⇒ newStr = '36'
large = 345
3rd Iteration
result = 6 + 3
⇒ result = 9
newStr = '36' + '9'
⇒ newStr = '369'
large = 45
Final value of newStr is '369'.
(iii) Given a first input of 123 and a second input of 4567, what result is produced by Line 3?
- 3
- 7
- 12
- 45
- None of these
Answer
Option 2 — 7
For loop executes 3 times as length of smaller input is 3. Initial value of large is 4567.
1st Iteration
large = large[1:]
⇒ large = 567
2nd Iteration large = large[1:]
⇒ large = 67
3rd Iteration large = large[1:]
⇒ large = 7
(iv) Given a first input of 123 and a second input of 4567, what result is produced by Line 4?
- 123
- 4567
- 7
- 3
- None of these
Answer
Option 1 — 123
As length of 123 is less than length of 4567 so 123 is assigned to variable small and gets printed in line 4.
Find the output if the input string is 'Test'.
S = input("Enter String :")
RS = " "
for ch in S :
RS = ch + RS
print(S + RS)Answer
TesttseT
The for loop reverses the input string and stores the reversed string in variable RS. After that original string and reversed string are concatenated and printed.
Find the output if the input string is 'Test'.
S = input("Enter String :")
RS = " "
for ch in S :
RS = ch + 2 + RS
print(S + RS)Answer
The program gives an error at line RS = ch + 2 + RS. The operands to + are a mix of string and integer which is not allowed in Python.
Find the errors. Find the line numbers causing errors.
- S = "PURA VIDA"
- print(S[9] + S[9 : 15])
Answer
The error is in line 2. Length of string S is 9 so its indexes range for 0 to 8. S[9] is causing error as we are trying to access out of bound index.
Find the errors. Find the line numbers causing errors.
- S = "PURA VIDA"
- S1 = S[: 10] +S[10 :]
- S2 = S[10] + S[-10]
Answer
The error is in line 3. Length of string S is 9 so its forward indexes range for 0 to 8 and backwards indexes range from -1 to -9. S[10] and S[-10] are trying to access out of bound indexes.
Find the errors. Find the line numbers causing errors.
- S = "PURA VIDA"
- S1 = S * 2
- S2 = S1[-19] + S1[-20]
- S3 = S1[-19 :]
Answer
The error is in line 3. S1[-19] and S1[-20] are trying to access out of bound indexes.
Find the errors. Find the line numbers causing errors.
- S = "PURA VIDA"
- S1 = S[: 5]
- S2 = S[5 :]
- S3 = S1 * S2
- S4 = S2 + '3'
- S5 = S1 + 3
Answer
The errors are in line 4 and line 6. Two strings cannot be multiplied. A string and an integer cannot be added.
What is the output produced?
(i) >>> "whenever" .find("never")
(ii) >>> "whenever" .find("what")
Answer
(i) 3
The starting index of substring "never" in "whenever" is 3.
(ii) -1
Substring "what" is not present in "whenever".
What is the output produced?
(i) >>> "-".join(['123','365','1319'])
(ii) >>> " ".join(['Python', 'is', 'fun'])
Answer
(i) '123-365-1319'
(ii) 'Python is fun'
Given a string S, write expressions to print
- first five characters of S
- Ninth character of S
- reversed S
- alternate characters from reversed S
Answer
- print(S[:5])
- print(S[8])
- for a in range(-1, (-len(S) - 1), -1) :
print(S[a], end = '') - for a in range(-1, (-len(S) - 1), -2) :
print(S[a], end = '')
Write a program to count the number of times a character occurs in the given string.
str = input("Enter the string: ")
ch = input("Enter the character to count: ");
c = str.count(ch)
print(ch, "occurs", c, "times")Enter the string: KnowledgeBoat
Enter the character to count: e
e occurs 2 times
Write a program which replaces all vowels in the string with '*'.
str = input("Enter the string: ")
newStr = ""
for ch in str :
lch = ch.lower()
if lch == 'a' \
or lch == 'e' \
or lch == 'i' \
or lch == 'o' \
or lch == 'u' :
newStr += '*'
else :
newStr += ch
print(newStr)Enter the string: Computer Studies
C*mp*t*r St*d**s
Write a program which reverses a string and stores the reversed string in a new string.
str = input("Enter the string: ")
newStr = ""
for ch in str :
newStr = ch + newStr
print(newStr)Enter the string: computer studies
seiduts retupmoc
Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input. Display if the phone number entered is valid format or not and display if the phone number is valid or not (i.e., contains just the digits and dash at specific places.)
phNo = input("Enter the phone number: ")
length = len(phNo)
if length == 12 \
and phNo[3] == "-" \
and phNo[7] == "-" \
and phNo[:3].isdigit() \
and phNo[4:7].isdigit() \
and phNo[8:].isdigit() :
print("Valid Phone Number")
else :
print("Invalid Phone Number")Enter the phone number: 017-555-1212
Valid Phone Number
=====================================
Enter the phone number: 017-5A5-1212
Invalid Phone Number
Write a program that should do the following :
- prompt the user for a string
- extract all the digits from the string
- If there are digits:
- sum the collected digits together
- print out the original string, the digits, the sum of the digits
- If there are no digits:
- print the original string and a message "has no digits"
Sample
- given the input : abc123
prints abc123 has the digits 123 which sum to 6 - given the input : abcd
prints abcd has no digits
str = input("Enter the string: ")
sum = 0
digitStr = ''
for ch in str :
if ch.isdigit() :
digitStr += ch
sum += int(ch)
if not digitStr :
print(str, "has no digits")
else :
print(str, "has the digits", digitStr, "which sum to", sum)Enter the string: abc123
abc123 has the digits 123 which sum to 6
=====================================
Enter the string: KnowledgeBoat
KnowledgeBoat has no digits
Write a program that should prompt the user to type some sentence(s) followed by "enter". It should then print the original sentence(s) and the following statistics relating to the sentence(s) :
- Number of words
- Number of characters (including white-space and punctuation)
- Percentage of characters that are alphanumeric
Hints
- Assume any consecutive sequence of non-blank characters is a word.
str = input("Enter a few sentences: ")
length = len(str)
spaceCount = 0
alnumCount = 0
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
alnumPercent = alnumCount / length * 100
print("Original Sentences:")
print(str)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length + 1))
print("Alphanumeric Percentage =", alnumPercent)Enter a few sentences: Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its implementation began in December 1989. Python 3.0 was released on 3 December 2008.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its implementation began in December 1989. Python 3.0 was released on 3 December 2008.
Number of words = 34
Number of characters = 206
Alphanumeric Percentage = 80.48780487804879
Write a Python program as per specifications given below:
- Repeatedly prompt for a sentence (string) or for 'q' to quit.
- Upon input of a sentence s, print the string produced from s by converting each lower case letter to upper case and each upper case letter to lower case.
- All other characters are left unchanged.
For example,
Please enter a sentence, or 'q' to quit : This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q ' to quit : What's up Doc ???
wHAT'S UP dOC ???
Please enter a sentence, or 'q' to quit : q
while True :
str = input("Please enter a sentence, or 'q' to quit : ")
newStr = ""
if str.lower() == "q" :
break
for ch in str :
if ch.islower() :
newStr += ch.upper()
elif ch.isupper() :
newStr += ch.lower()
else :
newStr += ch
print(newStr)Please enter a sentence, or 'q' to quit : This is the Bomb!
tHIS IS THE bOMB!
Please enter a sentence, or 'q' to quit : What's up Doc ???
wHAT'S UP dOC ???
Please enter a sentence, or 'q' to quit : q
Write a program that does the following :
- takes two inputs : the first, an integer and the second, a string
- from the input string extract all the digits, in the order they occurred, from the string.
- if no digits occur, set the extracted digits to 0
- add the integer input and the digits extracted from the string together as integers
- print a string of the form :
"integer_input + string_digits = sum"
For example :
For inputs 12, 'abc123' → '12 + 123 = 135'
For inputs 20, 'a5b6c7' → '20 + 567 =587'
For inputs 100, 'hi mom' → '100 + 0 = 100'
num = int(input("Enter an integer: "))
str = input("Enter the string: ")
digitsStr = ''
digitsNum = 0;
for ch in str :
if ch.isdigit() :
digitsStr += ch
if digitsStr :
digitsNum = int(digitsStr)
print(num, "+", digitsNum, "=", (num + digitsNum))Enter an integer: 12
Enter the string: abc123
12 + 123 = 135
=====================================
Enter an integer: 20
Enter the string: a5b6c7
20 + 567 = 587
=====================================
Enter an integer: 100
Enter the string: hi mom
100 + 0 = 100
Write a program that takes two strings from the user and displays the smaller string in single line and the larger string as per this format :
1st letter last letter
2nd letter 2nd last letter
3rd letter 3rd last letter
For example,
if the two strings entered are Python and PANDA then the output of the program should be :
PANDA
P n
y o
t h
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
small = str1
large = str2
if len(str1) > len(str2) :
large = str1
small = str2
print(small)
lenLarge = len(large)
for i in range(lenLarge // 2) :
print(' ' * i, large[i], ' ' * (lenLarge - 2 * i), large[lenLarge - i - 1], sep='')Enter first string: Python
Enter second string: PANDA
PANDA
P n
y o
t h
Write a program to convert a given number into equivalent Roman number (store its value as a string). You can use following guidelines to develop solution for it:
- From the given number, pick successive digits, using %10 and /10 to gather the digits from right to left.
- The rules for Roman Numerals involve using four pairs of symbols for ones and five, tens and fifties, hundreds and five hundreds. An additional symbol for thousands covers all the relevant bases.
- When a number is followed by the same or smaller number, it means addition. "II" is two 1's = 2. "VI" is 5 + 1 = 6.
- When one number is followed by a larger number, it means subtraction. "IX" is 1 before 10 = 9. "IIX isn't allowed, this would be "VIII". For numbers from 1 to 9, the symbols are "I" and "V", and the coding works like this. "I" , "II", "III", "IV", "V", "VI", "VII", "VIII", "IX".
- The same rules work for numbers from 10 to 90, using "X" and "L". For numbers from 100 to 900, using the symbols "C" and "D". For numbers between 1000 and 4000, using "M".
Here are some examples. 1994 = MCMXCIV, 1956 = MCMLVI, 3888= MMMDCCCLXXXVIII
n = int(input("Enter the number: "))
num = (1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1)
rom = ('M', 'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
result = ''
for i in range(len(num)) :
count = int(n / num[i])
result += str(rom[i] * count)
n -= num[i] * count
print(result)Enter the number: 1994
MCMXCIV
=====================================
Enter the number: 1956
MCMLVI
=====================================
Enter the number: 3888
MMMDCCCLXXXVIII
Write a program that asks the user for a string (only single space between words) and returns an estimate of how many words are in the string. (Hint. Count number of spaces)
str = input("Enter a string: ")
count = 0
for ch in str :
if ch.isspace() :
count += 1
print("No of words =", (count + 1))Enter a string: Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands.
No of words = 20
Write a program to input a formula with some brackets and checks, and prints out if the formula has the same number of opening and closing parentheses.
str = input("Enter a formula: ")
count = 0
for ch in str :
if ch == '(' :
count += 1
elif ch == ')' :
count -= 1
if count == 0 :
print("Formula has same number of opening and closing parentheses")
else :
print("Formula has unequal number of opening and closing parentheses")Enter a formula: s(s-a)(s-b)(s-c)
Formula has same number of opening and closing parentheses
=====================================
Enter a formula: s((s-a)(s-b)(s-c)
Formula has unequal number of opening and closing parentheses
Write a program that inputs a line of text and prints out the count of vowels in it.
str = input("Enter a string: ")
count = 0
for ch in str :
lch = ch.lower()
if lch == 'a' \
or lch == 'e' \
or lch == 'i' \
or lch == 'o' \
or lch == 'u' :
count += 1
print("Vowel Count =", count)Enter a string: Internet of Things
Vowel Count = 5
Write a program to input a line of text and print the biggest word (length wise) from it.
str = input("Enter a string: ")
words = str.split()
longWord = ''
for w in words :
if len(w) > len(longWord) :
longWord = w
print("Longest Word =", longWord)Enter a string: TATA FOOTBALL ACADEMY WILL PLAY AGAINST MOHAN BAGAN
Longest Word = FOOTBALL
Write a program to input a line of text and create a new line of text where each word of input line is reversed.
str = input("Enter a string: ")
words = str.split()
newStr = ""
for w in words :
rw = ""
for ch in w :
rw = ch + rw
newStr += rw + " "
print(newStr)Enter a string: Python is Fun
nohtyP si nuF