1

I create a file using this code:

file = open("full_names.txt", "wb")

file.write("Bob Smith\nMichael Jackson\nTony Tiger\nWinston Churchill\nHenry Kissinger\nHamid Karzai\nJohn Major\nJohnny Quest")

file.close()

I then run the script to print the file to screen:

with open("full_names.txt", "rb") as f:
    for line in f:
        first, last = line.strip().split(" ")
        print "Last Name: %r First Name: %r" % (last, first)

But the output shows up with quotes around the names, like this:

Last Name: 'Smith' First Name: 'Bob'

Does any one know why or how to get rid of them?

JDurstberger
  • 4,127
  • 8
  • 31
  • 68
user3426752
  • 415
  • 1
  • 8
  • 17

2 Answers2

7

if you replace %r with %s it should get rid of it.

%r shows the representation of the object which should reprsent a value that can be copied and pasted in the python shell to reproduce the object. %s will show the value of the object cast to a string.

As described in the docs https://docs.python.org/2/library/stdtypes.html#string-formatting


and repr because the concept is pretty cool: https://docs.python.org/2/library/functions.html#func-repr

dm03514
  • 54,664
  • 18
  • 108
  • 145
2

Simply because you're using %r. Change to %s and it will go away =)

print "Last Name: %s First Name: %" % (last, first)

%r is equivalent to repr(var) and %s is str(var)

Diogo Martins
  • 917
  • 7
  • 15