views:

103

answers:

3
+2  Q: 

Strings and file

Hello,

Suppose this is my list of languages.

aList = ['Python','C','C++','Java']

How can i write to a file like :

Python      : ...
C           : ...
C++         : ...
Java        : ...

I have used rjust() to achieve this. Without it how can i do ?

Here i have done manually. I want to avoid that,ie; it shuould be ordered automatically.

+5  A: 

You can do this with string formatting operators

f=open('filename.txt','w')
for item in aList:
    print >>f, "%-20s : ..." % item

The 20 is the field width, while the "-" indicates to left justify it.

Brian
+5  A: 

Do you mean this?

>>> languages = ['Python','C','C++','Java']
>>> f = open('myfile.txt', 'w')
>>> print('\n'.join('%-10s: ...' % l for l in languages), file=f)
>>> f.close()
>>> print(open('myfile.txt').read())
Python    : ...
C         : ...
C++       : ...
Java      : ...

This uses the format specification mini language. Note the print statement uses 3.0 syntax. (Yeah I changed this since Brian's answer links to the 2.5.2 docs. Just for contrast.)

Stephan202
A: 

Automatically determine colon position (using max width) and language order (sorted alphabetically):

languages = ['Python','C','C++','Java']
maxlen = max(map(len, languages))
with open('langs.txt', 'w') as f:
    for L in sorted(languages):
        f.write('%-*s: ...\n'% (maxlen, L)) 

print open('langs.txt').read()

Output:

C     : ...
C++   : ...
Java  : ...
Python: ...
J.F. Sebastian