String of Python

String of Python

Q1.What is a string in Python?

A. A sequence of integers
B. A sequence of characters
C. A sequence of floating-point numbers
D. A sequence of Boolean values

Answer: B

Explanation: In Python, a string is a sequence of characters enclosed in quotes. It can be defined using single quotes (‘…’) or double quotes (“…”).

Q2.Which of the following is a valid string in Python?

A. 1234
B. ‘1234’
C. 12.34
D. True

Answer: B

Explanation: ‘1234’ is a valid string in Python. A string can contain any sequence of characters, including digits, letters, and symbols.

Q3.What is the difference between single and double quotes in Python?

A. Single quotes can only be used for short strings, while double quotes can be used for longer strings.
B. Single quotes and double quotes are interchangeable.
C. Single quotes are used for strings, while double quotes are used for integers.
D. Single quotes are used for characters, while double quotes are used for strings.

Answer: B

Explanation: In Python, single and double quotes are interchangeable and can be used to define strings.

Q4.Which of the following is a valid way to concatenate two strings in Python?

A. str1 – str2
B. str1 + str2
C. str1 * str2
D. str1 / str2

Answer: B

Explanation: The + operator can be used to concatenate two strings in Python.

Q5.What is the result of the following code?

string1 = “Hello”
string2 = “World”
print(string1[1] + string2[3])

A. “Hd”
B. “eo”
C. “lW”
D. “ol”

Answer: C

Explanation: string1[1] is “e” and string2[3] is “d”, so the output is “lW”.

Q6.Which method can be used to convert a string to all lowercase letters in Python?

A. upper()
B. lower()
C. capitalize()
D. swapcase()

Answer: B

Explanation: The lower() method can be used to convert a string to all lowercase letters in Python.

Q7.Which method can be used to replace a substring in a string with a new substring in Python?

A. replace()
B. substr()
C. splice()
D. slice()

Answer: A

Explanation: The replace() method can be used to replace a substring in a string with a new substring in Python.

Q8.Which of the following is a valid way to access the length of a string in Python?

A. len(string)
B. string.length()
C. string.size()
D. length(string)

Answer: A

Explanation: The len() function can be used to access the length of a string in Python.

Q9.Which method can be used to split a string into a list of substrings based on a delimiter in Python?

A. join()
B. split()
C. replace()
D. substring()

Answer: B

Explanation: The split() method can be used to split a string into a list of substrings based on a delimiter in Python.

Q10.Which method can be used to remove whitespace from the beginning and end of a string in Python?

A. trim()
B. strip()
C. remove()
D. clean()

Answer: B

Explanation: The strip() method can be used to remove whitespace from the beginning and end of a string in Python

Q11.Which of the following is a valid way to check if a substring is present in a string in Python?

A. string.contains(substring)
B. substring.in(string)
C. string.find(substring)
D. substring.check(string)

Answer: B

Explanation: The in operator can be used to check if a substring is present in a string in Python. The correct syntax is substring in string.

Q12.Which method can be used to convert a string to a list of individual characters in Python?

A. split()
B. join()
C. list()
D. chars()

Answer: C

Explanation: The list() function can be used to convert a string to a list of individual characters in Python.

Q13.Which of the following is a valid way to format a string with variables in Python?

A. “Hello, {0} and {1}!”.format(name1, name2)
B. “Hello, %s and %s!” % (name1, name2)
C. f”Hello, {name1} and {name2}!”
D. All of the above

Answer: D

Explanation: All of the options are valid ways to format a string with variables in Python. Option A uses the format() method, option B uses the % operator, and option C uses f-strings.

Q14.Which method can be used to check if a string starts with a certain substring in Python?

A. startswith()
B. contains()
C. beginswith()
D. substr()

Answer: A

Explanation: The startswith() method can be used to check if a string starts with a certain substring in Python.

Q15.Which method can be used to check if a string ends with a certain substring in Python?

A. endswith()
B. contains()
C. finishswith()
D. substr()

Answer: A

Explanation: The endswith() method can be used to check if a string ends with a certain substring in Python.

Q16.What is string interpolation in Python?

A. The process of converting a string to a list of characters
B. The process of replacing variables in a string with their values
C. The process of encrypting a string for secure transmission
D. The process of compressing a string to save storage space

Answer: B

Explanation: String interpolation is the process of inserting variables or expressions into a string. In Python, this can be done using f-strings, format() method, or % operator.

Q17.What is a raw string in Python?

A. A string that is not encoded in any particular character set
B. A string that is used for regular expressions
C. A string that is formatted with variables
D. A string that treats all characters as literal characters, including backslashes

Answer: D

Explanation: A raw string in Python is a string that treats all characters as literal characters, including backslashes. It is defined using the letter ‘r’ before the opening quote.

String of Python

Q18.Which method can be used to count the number of occurrences of a substring in a string in Python?

A. count()
B. find()
C. index()
D. substring()

Answer: A

Explanation: The count() method can be used to count the number of occurrences of a substring in a string in Python.

Q19.Which method can be used to convert a string to uppercase letters in Python?

A. upper()
B. lower()
C. title()
D. capitalize()

Answer: A

Explanation: The upper() method can be used to convert a string to uppercase letters in Python.

Q20.What is the difference between a string and a byte string in Python?

A. A string is a sequence of characters, while a byte string is a sequence of bytes
B. A string is immutable, while a byte string is mutable
C. A string can only contain ASCII characters, while a byte string can contain any byte value
D. A string is represented using Unicode encoding, while a byte string is represented using a specific character encoding

Answer: A

Explanation: A string is a sequence of characters, while a byte string is a sequence of bytes. In Python, strings are represented using Unicode encoding, while byte strings are represented using a specific character encoding such as UTF-8 or ASCII.

Q21. Which method can be used to replace all occurrences of a substring in a string with a new substring in Python?

A. replace()
B. remove()
C. replace_all()
D. subst()

Answer: A

Explanation: The replace() method can be used to replace all occurrences of a substring in a string with a new substring in Python.

Q22.What is string slicing in Python?

A. The process of converting a string to a list of individual characters
B. The process of splitting a string into a list of substrings based on a delimiter
C. The process of extracting a portion of a string based on its position
D. The process of encoding a string using a specific character set

Answer: C

Explanation: String slicing in Python is the process of extracting a portion of a string based on its position. It can be done using square brackets and specifying the start and end indices of the substring to extract.

Q23. Which method can be used to check if a string contains only numeric characters in Python?

A. isdigit()
B. isnumeric()
C. isalpha()
D. isalnum()

Answer: A

Explanation: The isdigit() method can be used to check if a string contains only numeric characters in Python.

Q24.Which method can be used to concatenate two or more strings in Python?

A. concat()
B. merge()
C. join()
D. combine()

Answer: C

Explanation: The join() method can be used to concatenate two or more strings in Python. It is called on a separator string and the strings to be concatenated are passed as a list.

Q25.What is the difference between a string and a list in Python?

A. A string is mutable, while a list is immutable
B. A string can only contain characters, while a list can contain any data type
C. A string is indexed using square brackets, while a list is indexed using parentheses
D. A string is a sequence of characters, while a list is a sequence of values

Answer: D

Explanation: A string is a sequence of characters, while a list is a sequence of values. In Python, strings are immutable, meaning their values cannot be changed after they are created, while lists are mutable, meaning their values can be changed.

Q26.Which method can be used to remove leading and trailing whitespace characters from a string in Python?

A. lstrip()
B. rstrip()
C. strip()
D. remove()

Answer: C

Explanation: The strip() method can be used to remove leading and trailing whitespace characters from a string in Python.

Q27.Which method can be used to split a string into a list of substrings based on a delimiter in Python?

A. split()
B. join()
C. concatenate()
D. merge()

Answer: A

Explanation: The split() method can be used to split a string into a list of substrings based on a delimiter in Python. The delimiter can be specified as an argument to the method.

Q28.What is the difference between a string and a tuple in Python?

A. A string is mutable, while a tuple is immutable
B. A string can only contain characters, while a tuple can contain any data type
C. A string is indexed using square brackets, while a tuple is indexed using parentheses
D. A string is a sequence of characters, while a tuple is a sequence of values

Answer: D

Explanation: A string is a sequence of characters, while a tuple is a sequence of values. In Python, strings are immutable, meaning their values cannot be changed after they are created, while tuples are immutable, meaning their values cannot be changed.

Q29.Which method can be used to find the position of a substring in a string in Python?

A. find()
B. index()
C. search()
D. locate()

Answer: A

Explanation: The find() method can be used to find the position of a substring in a string in Python. If the substring is not found, the method returns -1.

book solution : Exception Handling in Python

Table of Content :

       1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement

.
       2. When are the following built-in exceptions raised? Give examples to support your answers.
a) ImportError
b) IOError
c) NameError
d) ZeroDivisionError

3. What is the use of a raise statement? Write a code to accept two numbers and display the quotient. Appropriate exception should be raised if the user enters the second number (denominator) as zero (0).

4. Use assert statement in Question No. 3 to test the division expression in the program.

5. Define the following:
a) Exception Handling
b) Throwing an exception
c) Catching an exception

6. Explain catching exceptions using try and except block

Q1. “Every syntax error is an exception but every exception cannot be a syntax error.” Justify the statement.

Answer : – The statement is true, and it highlights the difference between syntax errors and exceptions in programming.

In programming, syntax errors occur when the code violates the language’s syntax rules. For example, forgetting to close a parenthesis or using an undefined variable. These errors are detected by the compiler or interpreter during the compilation or interpretation phase and prevent the code from running. Thus, every syntax error is an exception because it breaks the normal flow of the program execution.

On the other hand, exceptions are errors that occur during the execution of a program. These errors are not necessarily caused by syntax violations, but rather by unexpected events, such as a division by zero, an invalid file operation, or a network error. Exceptions can be handled by the program to prevent it from crashing, and they may or may not be caused by syntax errors. Therefore, every exception cannot be a syntax error because an exception can be caused by a logical error or an external event that is not related to syntax violations.

In summary, every syntax error is an exception because it interrupts the normal program flow, but every exception cannot be a syntax error because exceptions can be caused by a wide range of unexpected events, not necessarily syntax violations.

Page : 1           2           3           4

Chapter 1 : Exception Handling in Python theory

Syntax Errors in python
Syntax errors in Python are errors that occur when the interpreter encounters code that violates the rules of the Python language syntax. In other words, syntax errors occur when there is a mistake in the way the code is written, such as a missing colon or parentheses.

Here’s an example of a syntax error:

bash
Copy code
print(“Hello, world!”
This code is missing a closing parentheses for the print function, which results in a syntax error. When you run this code, you will see an error message that looks something like this:

arduino
Copy code
File “<stdin>”, line 1
print(“Hello, world!”
^
SyntaxError: unexpected EOF while parsing
The error message indicates that the interpreter encountered an unexpected end of file while trying to parse the code.

Other examples of syntax errors include:

Missing colon after an if statement
Missing parentheses around function arguments
Using an invalid keyword as a variable name
Syntax errors are usually easy to fix once you identify them. The error message will give you a clue as to where the error is located in your code.

Page : 1           2           3           4

12 Class- Exception Handling in Python

What are exceptions?
Exceptions are events that occur during program execution that disrupt the normal flow of the program and can lead to errors. Examples of exceptions include division by zero, invalid input, file not found, etc.

Handling exceptions
In Python, exceptions can be handled using the try-except block. The code that might raise an exception is placed inside the try block, and the code to handle the exception is placed inside the except block.

Types of exceptions
Python has many built-in exceptions, including NameError, TypeError, ValueError, ZeroDivisionError, etc. It is also possible to create custom exceptions using the raise statement.

Raising exceptions
Developers can raise exceptions manually using the raise statement. This is useful when an error occurs that cannot be handled by the program, and it needs to be passed on to a higher-level function or the user.

Finally block
The finally block is a piece of code that is executed whether or not an exception is raised. It is typically used for cleanup code, such as closing files or releasing resources.

Exception hierarchy
Python has a hierarchy of exception classes, with the base class being Exception. This allows developers to catch multiple exceptions at once using a single except block.

Debugging
Exception handling is an essential tool for debugging Python programs. By handling exceptions gracefully, developers can identify and fix errors in their code more easily.

Page : 1           2           3           4