python interview questions

Q1. Convert a given string to int using a single line of code.

Example:

If the string is "108", it should be converted to the integer 108.

Code:

a = ‘9’

print (int(a))

Explanation:

In Python, you can convert a string that represents a number to an integer using the built-in int() function. This is a straightforward and efficient way to perform the conversion in a single line of code.

a = ‘9’

print (int(a))

Q2. Write a code to convert a string to a list.

Example:

Let’s say you have the string "hello" and you want to convert it to a list of its characters. Then output should be [‘h’, ‘e’, ‘l’, ‘l’, ‘o’]

Code:

string = “hello”

char_list = list(string)

print(char_list)

Explanation:

The list () function is a built-in function in Python that converts an iterable (like a string) to a list.

The function takes a single argument, which in this case is the string "hello"

The list() function processes the string and converts it to a list where each character of the string becomes a separate element in the list.

string = "hello"

char_list = list(string)

print(char_list)
g3b8d9db8355776319401806ff18a2022f713f1683d18c39207a9de147709310f802fde75c5a5f51aa5b163de6a0ffbe41bb7bd0c0dd7b081ea8810e899f31002_1280-4245029.jpg

Q3. Write a code to reverse a string.

Example:

Let’s say you have the string "hello" and you want to reverse it.

Then output should be olleh

Code:

reversed_string = “hello”[::-1]

print(reversed_string)

Explanation:

Slicing allows you to access a subset of a sequence (like a string) by specifying a start, stop, and step.

Slice notation [::-1] means “start from the end of the string and move backwards by one step at a time” until you reach the beginning.

reversed_string = "hello"[::-1]

print(reversed_string)

2 thoughts on “python interview questions”

Leave a Comment

Your email address will not be published. Required fields are marked *