31. What is __init__.py?
It is used to import a module in a directory, which is called package import.
32. Print contents of a file ensuring proper error handling?
print”No such file exists”
33. How do we share global variables across modules in Python?
We can create a config file and store the entire global variable to be shared across modules in it. By simply importing config, the entire global variable defined will be available for use in other modules.
For example I want a, b & c to share between modules.
print(“a,b &resp.are :”,config.a,config.b,config.c)
Output of module1.py will be
34. Does Python support Multithreading?
35. How do I get a list of all files (and directories) in a given directory in Python?
Following is one possible solution there can be other similar ones:
for dir name,dirnames,filenames inos.walk(‘.’):
# print path to all subdirectories first.
for subdirname in dirnames:
# print path to all filenames.
for filename in filenames:
# Advanced usage:
# editing the ‘dirnames’ list will stop os.walk() from recursing into there.
if ‘.git’ in dirnames:
# don’t go into any .git directories.
36. How to append to a string in Python?
The easiest way is to use the += operator. If the string is a list of character, join() function can also be used.
37. How to convert a string to lowercase in Python?
use lower() function.
38. How to convert a string to lowercase in Python?
Similar to the above question. use upper() function instead.
39. How to check if string A is substring of string B?
The easiest way is to use the in operator.
‘abc’ in ‘abcdefg’
40. Find all occurrences of a substring in Python
There is no simple builtin string function that does what you’re looking for, but you could use the more powerful regular expressions:
>>>[m.start()form inre.finditer(‘test’,’test test test test’)] [0,5,10,15]
// these are starting indices for the string.