0
>>>line=['hello',' this',' is', 'a',' test']  
>>>print line
['hello', 'this', 'is', 'a', 'test']

But i want that when line is printed, it should be a whole string and not like elements of a list. This is what i tried:

>>> print line[k] for k in len(line)
SyntaxError: invalid syntax

How can this list line can be printed as a string?

Mazdak
  • 105,000
  • 18
  • 159
  • 188

2 Answers2

1

There are a few different ways to concatenate strings in python. If you have a list and want to concatenate its contents, the preferred way is usually .join(list).

line=['hello',' this',' is', ' a',' test']
print ''.join(line)

For more ways see http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python

If you wanted to use a for loop (not recommended, but possible) you could do something like

line=['hello',' this',' is', ' a',' test']
concatenated_line = ''

for word in line:
    concatenated_line += word

print concatenated_line
Barnabus
  • 376
  • 3
  • 14
0
line=['hello',' this',' is', 'a',' test'] 
str1 = ' '.join(line)
print str1
# hello this is a test
Peter Wang
  • 1,808
  • 1
  • 11
  • 28
  • But i want this to be printed in the same line with other things as well – Harshita Agrawal Jul 09 '16 at 13:59
  • While code often speaks for itself, it's good to add some explanation to your code. This popped up in the review queue, as code-only answers tend to. – Will Jul 09 '16 at 19:19