0

I have the following list of strings of integers:

li = ['1', '2', '3', '4', '5', '6', '7']

What does my code need to be for my output to be the following?:

1 2 3 4 5 6 7

I tried doing both:

" ".join(str(val) for val in li)

and

" ".join(li)

but both of them don't work.

I want to get rid of the brackets, the quotation marks, and the commas.

Zombo
  • 1
  • 62
  • 391
  • 407
qlzlahs
  • 73
  • 2
  • 9
  • Do you want to save that as a string, or just print it? – TigerhawkT3 Aug 01 '15 at 23:57
  • I want to save it so that I can use it somewhere else. @TigerhawkT3 – qlzlahs Aug 01 '15 at 23:58
  • Both of those solutions should already work. Remember that if you just enter an expression at the interpreter, it'll output the `__repr__()` of the returned object, which will produce `'1 2 3 4 5 6 7'` for this. If you don't want the quotes, use the actual `print()` function. – TigerhawkT3 Aug 01 '15 at 23:59
  • You mean to print it to some output stream, e.g. a file object. First do as suggested: ```out = ' '.join( ['1','2','3'] )```. Next , ```f = open('test.txt', 'w')``` ; ```f.write( out )``` ; ```f.close()``` or ```print(out)```. I have to assume this is what you want to do because your statement **"get rid of the brackets, quotations ... etc "** makes little sense when speaking about a variable within a python routine. – dermen Aug 04 '15 at 00:52

1 Answers1

1

You can use map to apply int() to every element in the list:

map(int, ['1', '2', '3', '4', '5', '6', '7']) # [1, 2, 3, 4, 5, 6, 7]

If you just want to print the numbers as a string, you can simply do:

' '.join(['1', '2', '3', '4', '5', '6', '7']) # 1 2 3 4 5 6 7
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
  • Does map(int, li) work as well? I just set a different variable list1 equal to a list of big numbers in quotation marks ['150', '230', '132', '184', '353'], did map(int, list1) and then did " ".join(list1) but I get the error "ValueError: invalid literal for int() with base 10." @alfasin – qlzlahs Aug 01 '15 at 23:57
  • This question has been answered before, for example at http://stackoverflow.com/questions/10351772/converting-list-of-string-to-list-of-integer. @alfasin - this could be a reason for downvoting however that was already done when I viewed the question. –  Aug 01 '15 at 23:57
  • @TrisNefzger the right reaction should be voting to close as dup - not to downvote answers. oh well... Thanks for your comment! – Nir Alfasi Aug 01 '15 at 23:59
  • @qlzlahs you mixed both answers... I showed you two options - you should use either the first or the second - not both at the same time ;) – Nir Alfasi Aug 02 '15 at 00:00