1

I've seen answers to this questions in SO, like here, and here. However, using the methods they suggested, the output I get in the file looks partly shifted.

Specifically, I've got a list of tuples, consisting of a number and a string. Using this solution, for example:

for t in sorted_words:
      wrds.write(''.join(str(s) for s in t) + ' ')

What I get in the file is of the following format:

wordone
0.0 wordtwo
0.0 wordthree
0.0 wordfour
0.0 

Any explanation for this? Thank you!

Community
  • 1
  • 1
Cheshie
  • 2,777
  • 6
  • 32
  • 51
  • 2
    Can you expand the source code, show the tuple `sorted_words` at least? – Paulo Bu Jan 21 '14 at 16:48
  • Thanks @Paulo, for the edit (I forgot how to style codes here...). You're right to ask for `sorted_words`, that's where my error was, as user2357112 pointed out. Thanks so much anyway! – Cheshie Jan 21 '14 at 17:03

2 Answers2

3

Your word strings have newlines at the end of them.

If you want output in the following form:

wordone 0.0
wordtwo 0.0
wordthree 0.0

you should take the newlines off, then use

for word, weight_or_whatever in sorted_words:
    wrds.write("{} {}\n".format(word, weight_or_whatever))

(I'm not sure what the numbers represent.)

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Thanks so much @user2357112! You're absolutely right... sorry about the stupid mistake (I'm using encoded strings and they're so long I didn't really notice the \n...excuses ;-) ). – Cheshie Jan 21 '14 at 17:01
2

As user2357112 pointed out, your strings have newlines at the end, so you can use strip() which removes leading and trailing whitespace, including newlines.

for t in sorted_words:
      wrds.write(' '.join(str(s).strip() for s in t) + '\n')
Diego Herranz
  • 2,857
  • 2
  • 19
  • 34