Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strings and file

Tags:

python

string

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.

like image 327
user46646 Avatar asked Feb 13 '26 07:02

user46646


1 Answers

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.)

like image 158
Stephan202 Avatar answered Feb 15 '26 22:02

Stephan202



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!