Changing a list into a string - python

I have a list like this:
li = [1, 2, 3, 4, 5]
I want to change it into a string, get rid of the quotes, and get rid of the commas so that it looks like this:
1 2 3 4 5
I tried the following:
new_list = []
new_list.append(li)
new_string = " ".join(new_list)
print new_string
however I get the below error:
TypeError: sequence item 0: expected str instance, int found
Why does this happen and how can I fix this so that I get the output I want?

The items in the list need to be of the str type in order to join them with the given delimeter. Try this:
' '.join(map(str, your_list)) # join the resulting iterable of strings, after casting ints

This is happening because join is expecting an iterable sequence of strings, and yours contains int.
You need to convert this list to string either by using list comprehension:
>>> li
[1, 2, 3, 4, 5]
>>> new_li = [str(val) for val in li]
>>> new_li
['1', '2', '3', '4', '5']
or a regular for loop:
>>> for x in range(len(li)):
... li[x] = str(li[x])
...
>>> li
['1', '2', '3', '4', '5']
then your expression will work.
>>> result = ' '.join(li)
>>> result
'1 2 3 4 5'

The error is from attempting to join integers into a string, you could do this to turn every value into a string, then join them.
new_list = [str(x) for x in li]
new_string = " ".join(new_list)
As a one-liner:
new_string = " ".join([str(x) for x in li])

Related

Replace consecutive delimiters in string with values from list

I have a string, for example:
s = "I ? am ? a ? string"
And I have a list equal in length to the number of ? in the string:
l = ['1', '2', '3']
What is a pythonic way to return s with each consecutive ? replaced with the values in l?, e.g.:
s_new = 'I 1 am 2 a 3 string'
2 Methods:
# Method 1
s = "I ? am ? a ? string"
l = ['1', '2', '3']
for i in l:
s = s.replace('?', i, 1)
print(s)
# Output: I 1 am 2 a 3 string
# Method 2
from functools import reduce
s = "I ? am ? a ? string"
l = ['1', '2', '3']
s_new = reduce(lambda x, y: x.replace('?', y, 1), l, s)
print(s_new)
# Output: I 1 am 2 a 3 string
If the placeholders (not "delimiters") were {} rather than ?, this would be exactly how the built-in .format method handles empty {} (along with a lot more power). So, we can simply replace the placeholders first, and then use that functionality:
>>> s = "I ? am ? a ? string"
>>> l = ['1', '2', '3']
>>> s.replace('?', '{}').format(*l)
'I 1 am 2 a 3 string'
Notice that .format expects each value as a separate argument, so we use * to unpack the list.
If the original string contains { or } which must be preserved, we can first escape them by doubling them up:
>>> s = "I ? {am} ? a ? string"
>>> l = ['1', '2', '3']
>>> s.replace('?', '{}').format(*l)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'am'
>>> s.replace('{', '{{').replace('}', '}}').replace('?', '{}').format(*l)
'I 1 {am} 2 a 3 string'

How to convert list elements to string using Python?

How should I convert list elements to string using Python?
For example I have a list that looks like this:
[1, 2, 3, 4, 5]
And I want it to look like this:
['1', '2', '3', '4', '5']
Use a one-liner to iterate over all elements it an Iterable and use str(element) to cast the element as a string
new_list = [str(i) for i in old_list]
def listToString(a):
li = []
for i in a:
li.append(str(i))
return li
We can input the list in the function.

python splitting string twice

I'm trying to split a string twice with the goal of converting a>b where b contains numbers and is split into multiple x/y pairs
a = '{1;5}{2;7}{3;9}{4;8}'
b = [[1,5],[2,7],[3,9],[4,8]]
my code is currently this...
b = a.split('}{')
for item in b:
item.replace('{','')
item.replace('}','')
item.split(';')
the first split works correctly and returns this
b = ['{1;5','2;7','3;9','4;8}']
but manipulating the 'items in b' does not appear to work
You can use a list comprehension to do both splits at once and return a list of lists:
>>> a = '{1;5}{2;7}{3;9}{4;8}'
>>> [item.split(';') for item in a[1:-1].split('}{')]
[['1', '5'], ['2', '7'], ['3', '9'], ['4', '8']]
You have to actually modify the list b by interacting with its item. You should do something like this:
for i, s in enumerate(b):
b[i] = s.replace('{','')
b[i] = s.replace('}','')
b[i] = s.split(';')
In [9]: b
Out[9]: [['{1', '5'], ['2', '7'], ['3', '9'], ['4', '8}']]
I dont know if that's your expected output
Here are two examples where you are not affecting the list b
for item in b:
item = item.replace('{','')
item = item.replace('}','')
item = item.split(';')
In [21]: b = ['{1;5','2;7','3;9','4;8}']
In [22]: for item in b:
item = item.replace('{','')
item = item.replace('}','')
item = item.split(';')
In [23]: b
Out[23]: ['{1;5', '2;7', '3;9', '4;8}']
This one wouldnt do anything to the list b neither.
for item in b:
item.replace('{','')
item.replace('}','')
item.split(';')
This can also be done using regular expressions.
The items you are looking for inside the input string consist of
two numbers \d+
separated by a semicolon ;
enclosed in curly braces \{, \}.
The complete pattern looks like this:
pattern = r'\{(\d+);(\d+)\}'
The additional parentheses () define groups which allow extracting the numbers, for example with re.findall:
>>> for item in re.findall(pattern, a):
>>> print item
('1', '5')
('2', '7')
('3', '9')
('4', '8')
Then it is a simple matter of mapping int over the items to get the desired result:
>>> [map(int, item) for item in re.findall(pattern, a)]
[[1, 5], [2, 7], [3, 9], [4, 8]]
Some prefer list comprehensions over map:
>>> [[int(x) for x in item] for item in re.findall(pattern, a)]
[[1, 5], [2, 7], [3, 9], [4, 8]]
The function call
item.replace('{','')
does not do anything to item, since it returns a new string after the replacement. Instead, try:
item = item.replace('{','')
Similar changes need to be made for the other lines in that block.

Partitioning elements in list by \t . Python

my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
I'm trying to split this list into sublists separated by \t
output = [['1','Melkor','Morgoth','SauronAtDolGoldul'],['2','Thigols','HeirIsDior','Silmaril'],['3','Arkenstone','IsProbablyA','Silmaril']]
I was thinking something on the lines of
output = []
for k_string in my_list:
temp = []
for i in k_string:
temp_s = ''
if i != '\':
temp_s = temp_s + i
elif i == '\':
break
temp.append(temp_s)
it gets messed up with the t . . i'm not sure how else I would go about doing it. I've seen people use .join for similar things but I don't really understand how to use .join
You want to use str.split(); a list comprehension lets you apply this to all elements in one line:
output = [sub.split('\t') for sub in my_list]
There is no literal \ in the string; the \t is an escape code that signifies the tab character.
Demo:
>>> my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
>>> [sub.split('\t') for sub in my_list]
[['1', 'Melkor', 'Morgoth', 'SauronAtDolGoldul'], ['2', 'Thingols', 'HeirIsDior', 'Silmaril'], ['3', 'Arkenstone', 'IsProbablyA', 'Silmaril']]
>>> import csv
>>> my_list = ['1\tMelkor\tMorgoth\tSauronAtDolGoldul','2\tThingols\tHeirIsDior\tSilmaril','3\tArkenstone\tIsProbablyA\tSilmaril']
>>> list(csv.reader(my_list, delimiter='\t'))
[['1', 'Melkor', 'Morgoth', 'SauronAtDolGoldul'], ['2', 'Thingols', 'HeirIsDior', 'Silmaril'], ['3', 'Arkenstone', 'IsProbablyA', 'Silmaril']]

Merging items in a list - Python

Say I have a list in python, like such:
list=[1,2,3,4,5]
How would I merge the list so that it becomes:
list= [12345]
If anyone has a way to do this, it would be greatly appreciated!!
reduce(lambda x,y:10*x+y, [1,2,3,4,5])
# returns 12345
This probably better:
"%s" * len(L) % tuple(L)
which can handle:
>>> L=[1, 2, 3, '456', '7', 8]
>>> "%s"*len(L) % tuple(L)
'12345678'
>>> list=[1,2,3,4,5]
>>> k = [str(x) for x in list]
>>> k
['1', '2', '3', '4', '5']
>>> "".join(k)
'12345'
>>> ["".join(k)]
['12345']
>>>
>>> [int("".join(k))]
[12345]
>>>
list=[int("".join(map(str,list)))]
a = [1,2,3,4,5]
result = [int("".join(str(x) for x in a))]
Is this really what you mean by "merge the list"? You understand that a Python list can contain things other than numbers, right? You understand that Python is strongly typed, and will not let you "add" strings to numbers or vice-versa, right? What should the result be of "merging" the list [1, 2, "hi mom"] ?
[int(reduce(lambda x,y: str(x) + str(y),range(1,6)))]

Categories