Python Interviews: Difference between revisions
→"is" vs "=="
(12 intermediate revisions by the same user not shown) | |||
Line 6:
= Open a file =
f = open('text.txt','r')
l = f.readlines()
f.close()
for i in l:
print(i.strip('\n'))
= Read Log File =
* Better way to open a file as it auto closed file, even on crash
<pre>
with open('/var/log/apache2/access.log','r') as file:
for line in file:
print(line.split()[3], line.split()[6], line.split()[8], line.split()[9])
try:
b = b +int(line.split()[9])
except:
pass
print(b)
</pre>
= List Comprehension =
Line 191 ⟶ 208:
= Regex =
Positive lookahead (?=REGEX_1)REGEX_2 (?=regex) t(?=s) matches the second t in streets.
Negative lookahead (?!REGEX_1)REGEX_2 (?!regex) t(?!s) matches the first t in streets.
Positive lookbehind (?<=regex) (?<=s)t matches the first t in streets.
Negative lookbehind (?<!regex) (?<!s)t matches the second t in streets.
= Sum Function =
lst = []
num = int(input('How many numbers: '))
for n in range(num):
numbers = int(input('Enter number '))
lst.append(numbers)
print("Sum of elements in given list is :", sum(lst))
= Convert Numeral System =
for i in range(0,10):
print(i, oct(i), hex(i), bin(i))
for i in range(0,10):
print(i, oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:])
= Justify Text =
text.rjust(3,' ')
text.ljust(3,' ')
text.center(3,' ')
= Formatting =
[https://pyformat.info/ pyformat.info]
Old Method:
print('%s %s' % ('one','two'))
New Method:
print('{} {}'.format('one','two'))
Positional Index:
print('{1} {0}'.format(56,'ld'))
= Sorting =
listed ={}
plist = set(port_list)
listed.update({v:sorted(plist)})
for k,v in listed.items():
print("Tenant: ", k, "\nNo of Ports: ", len(v), '\n', [i for i in v if len(v) >0], '\n')
c = [1,5,2,3,9,6,2,0]
c.sort()
= Reverse a String =
'hello world'[::-1]
'dlrow olleh'
= Convert to Positive Number =
>>> a = -30
>>> abs(a)
30
* Interger can be positive or Negative:
>>> int(a)
-30
>>> -a
30
>>> c = 30.9
>>> int(c)
30
= "is" vs "==" =
a = [1,2,3]
b = a
c = [1,2,3]
print(a==c)
print(a is c)
Output:
True
False
= Dictionary =
a = {}
|