0
def catenateLoop(strs):
    outputString = ""
    for strings in strs:
        outputString = outputString + strings         
    print outputString

I'm using the code above to concatenate a list of strings into a single string using a for loop. Right no the code is outputting the correct concatenation, but for some reason the code is not being outputted as a string. For example, catenateLoop(['one', 'two', 'three']) is printing onetwothree instead of 'onetwothree'. I've tried several different formats but I can't seem to figure out why it won't print in a string. Any ideas?

3 Answers3

0

"print" only prints out the contents of outputString; if you want to output the representation of outputString (which will include quotes), try "print repr(outputString)".

KJ4TIP
  • 166
  • 3
0

__repr__ to the rescue!

This will give you the desired result

def catenateLoop(strs):
    outputString = ""
    for strings in strs:
        outputString = outputString + strings         
    print repr(outputString)

catenateLoop(['one', 'two', 'three'])

#output: 'onetwothree'

Also see Why are some Python strings are printed with quotes and some are printed without quotes?

Community
  • 1
  • 1
Tim
  • 41,901
  • 18
  • 127
  • 145
  • If I wanted a defined output I wouldn't rely on `repr`. – Matthias Oct 29 '14 at 21:30
  • @Matthias can you tell me what you mean by 'defined output'? – Tim Oct 29 '14 at 21:34
  • `repr` gives you the printable representation of an object and this representation might change in future versions of Python (or by monkey patching). I'd use it for debugging purposes, but not to get a well-defined output. – Matthias Oct 30 '14 at 07:12
  • @Matthias I have to agree – Tim Oct 30 '14 at 08:08
0

You can use str.format and wrap the output in whatever you want:

def catenateLoop(strs):
    outputString = ""
    for strings in strs:
        outputString = outputString + strings
    print "'{}'".format(outputString)

In [5]: catenateLoop(['one', 'two', 'three'])
'onetwothree'

You can also use str.join to concatenate the list contents:

def catenateLoop(strs):
    print "'{}'".format("".join(strs))
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321