0
def formatWords(words):
  result = "Word List:\tWord Count:\n"
  for i in words:
    result += i + ":\t" + str(words.count(i)) + "\n"
  return result

words is just an array of strings.

I am supposed to get an output of

Desired Output

I get the output of

enter image description here

How do I format the string to look like the first picture?

JPHamlett
  • 365
  • 3
  • 9
  • Several dups of this question, e.g. http://stackoverflow.com/questions/19103052/python-string-formatting-columns-in-line – Tim McNamara Jul 20 '15 at 02:40

3 Answers3

1

Use the string method ljust():

result += (i+':').ljust(20) + str(words.count(i)) + '\n'

20 is the total size of that string, padded by however many spaces are needed to end up with that size.

TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
1

Example 1:

row_format = "{:<15}" * 2
rows = [('word list:', 'word_count'),
        ('brown', 1),
        ('dog', 1)]
for row in rows:
    print row_format.format(*row)

output:

word list:     word_count     
brown          1              
dog            1     

Example 2:

row_format = "{:<15}{:^15}"
rows = [('word list:', 'word_count'),
        ('brown', 1),
        ('dog', 1)]
for row in rows:
    print row_format.format(*row)  

output:

word list:       word_count   
brown                 1       
dog                   1     

Format Specification Mini-Languagegives more details.

letiantian
  • 437
  • 2
  • 14
0

Use format function.

result += "{:<20}{:<30}\n".format(i, words.count(i))
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274