Python - Functions Question & Answer



Qus. What is a string slice? How is it useful?

Ans: String Slice is a part of a string containing some contiguous characters from the string. It is accessed from the string by providing a range in ―[ ]‖ brackets i.e. S [n:m]. Python returns all the characters at indices n, n+1, n+2 . . . m-1 e.g. 'Barabanki'.[4:7] will return 'ban'.

Qus. Which functions would you chose to use to remove leading and trailing white spaces from a given string?

Ans: Python String strip() function will remove leading and trailing white spaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

Qus. Suggest appropriate functions for the following tasks –

(a) To check whether the string contains digits.

(b) To find the occurrence a string within another string.

(c) To convert the first letter of a string to upper case.

(d) To convert all the letters of a string to upper case.

(f) To check whether all the letters of the string are in capital letters.

(g) to remove all the white spaces from the beginning of a string.

Ans.  (a) isalnum() (b) find() (c) capitalize()   (d) upper() (f) isupper() (g) lstrip()