Question

I'm trying to join each word from a .txt list to a string eg{ 'word' + str(1) = 'word1' } with this code:

def function(item):
  for i in range(2):
    print item + str(i)

with open('dump/test.txt') as f:
  for line in f:
    function(str(line))

I'll just use a txt file containing just two words ('this', 'that'). What I get is:

this
0
this
1
that0
that1

What I was expecting:

this0
this1
that0
that1

It works fine if I just use function('this') and function('that') but why doesn't it work with the txt input?

--- Edit: Solved, thank you! Problem was caused by

newline characters in the strings received

Solution: see Answers

Was it helpful?

Solution

You should change

print item + str(i)

to

print item.rstrip() + str(i)

This will remove any newline characters in the strings received in function.


A couple of other tips:

  1. A better way to print data is to use the .format method, e.g. in your case:

    print '{}{}'.format(item.strip(), i)
    

    This method is very flexible if you have a more complicated task.

  2. All rows read from a file are strings - you don't have to call str() on them.

OTHER TIPS

The first line read by python is this\n and when you append 0 and 1 to this you get this\n0 and this\n1. Whereas in case in the second line you are not having a new line at the end of the file (inferring from what you are getting on printing). So appending is working fine for it.

For removing the \n from the right end of the string you should use rstrip('\n')

print (item.rstrip('\n') + str(i))

In the first "This\n" is there that's why you are getting not formatted output. pass the argument after removing new line char.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top