convert to string: list with integers and strings
How do I get datalist to string?
>>> days = 24/6
>>> print days
4
>>> hours = 45/7
>>> print hours
6
>>> datalist = []
>>> datalist.append(days)
>>> datalist.append(" days ")
>>> print datalist
[4, ' days ']
>>> datalist_str = "".join(datalist)
Traceback (most recent call last):
File "", line 1, in ?
TypeError: sequence item 0: expected string, int found
jobs
Junior Poster in Training
58 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
- print " ".join(["%s" % el for el in datalist])
This means, take take el from datalist, convert it to string "%s" % el, and put into the list.
Correct me if I am wrong.
jobs
Junior Poster in Training
58 posts since Jan 2007
Reputation Points: 10
Solved Threads: 0
Next time please push start a new thread button from the Python groups main list so your post will be better seen.
I push this [code] here, that gives nice looking fixed width text and keeps the white space, which is so essential for Python. Use also that next time when you some code stuff.
This is from interactive Python prompt as your request was so simple.
>>> short_list = ['a\n' , 'b\n', 'c\n']
>>> var_a, var_b, var_c = [ x.rstrip() for x in short_list ] ## rstrip newline out and assign
>>> var_a, var_b, var_c
('a', 'b', 'c')
>>>
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852
It's a trick question because you don't store the values in a separate variable (that's why we have lists), you use
short_list[0].strip()
short_list[1].strip()
short_list[2].strip()
or strip all of the values in short_list if you don't want to strip() each time.
short_list = ['a\n' , 'b\n', 'c\n']
for x in range(len(short_list)):
short_list[x] = short_list[x].strip()
woooee
Nearly a Posting Maven
2,454 posts since Dec 2006
Reputation Points: 777
Solved Threads: 714
You are welcome but consider that generally it is not so much necessary put list
elements to different variables if you use lists properly.
Consider therefore also this using [index] to get the elements. In that case be careful in that index goes from 0 until length-1.
short_list = [ x.rstrip() for x in short_list ] ## rstrip newline out
pyTony
pyMod
5,359 posts since Apr 2010
Reputation Points: 782
Solved Threads: 852