x = raw_input("Enter value: ")The input comes in as a string and you need to convert it to the appropriate representation using a cast. For example, to convert x to an int, you would use int(x).
import sys # sys is not pre-defined for line in sys.stdin: process the line of input
>>> x = 10 >>> y = 'brad' >>> 'x = {0:8d} and y = {1:20s}--correct?'.format(x,y) 'x = 10 and y = brad --correct?' >>> 'x = {0:<8d} and y = {1:^20s}--correct?'.format(x,y) 'x = 10 and y = brad --correct?'
>>> x = [1, 2, 3, 4] >>> 'x[1] = {0[1]}'.format(x) 'x[1] = 2'
[[fill]align][width][.precision][type]
Option | Meaning |
---|---|
< | left align |
> | right align |
^ | center |
>>> with open('workfile', 'r') as f: ... read_data = f.read()When with exits for any reason, the file is automatically closed.
for line in f: ... process line ...
f.write(str(20))
myfile.write('\n'.join(lines))
>>> import json >>> a [3, 4, 5] >>> x {'nels': 5, 'brad': 3} >>> writeList = [a, x, 543] >>> json.dump(writeList, f)