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.
Related
for solving above problem I normally use for loop like that:
list1 = ['1', '2', 3,32423,5.76, "afef"]
list2 = []
for ele in list1:
list2.append(str(ele))
does python has some build in function for solving that problem?
You can use the built-in function map like the following:
list1 = ['1', '2', 3, 32423, 5.76, "afef"]
list2 = list(map(str, list1))
I have a list like this:
list = ['aa#1#ll', 'bb#2#ff', 'cc#3#ff']
I want to convert it to a 2D list in this format
list2 = [['aa', '1', 'll'], ['bb', '2', 'ff'], ['cc', '3', 'ff']]
How can I do this in Python 3?
You can use Python's split(delimiter) method inside a generator:
list2 = [x.split("#") for x in list]
Explanation: Here, for each string x in the original list, we are calling x.split("#") on it, which will give a list of substrings that are separated by hashes in x, and we are adding the result to the list list2.
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])
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.
For example:
list = [[11,2,3,5],[5,3,74,1,90]]
returns the same thing, only everything is a str instead of an int.
I want to be able to use .join on them. Thanks!
If you only ever go 2 lists deep:
>>> l = [[11, 2, 3, 5], [5, 3, 74, 1, 90]]
>>> [[str(j) for j in i] for i in l]
[['11', '2', '3', '5'], ['5', '3', '74', '1', '90']]
I'd use a list-comp and map for this one:
[ map(str,x) for x in lst ]
But I suppose py3.x would need an addition list in there (yuck).
[ list(map(str,x)) for x in lst ]
As a side note, you can't use join on this list we return anyway. I'm guessing you want to do something like this:
for x in lst:
print ("".join(x))
If that's the case, you can forgo the conversion all together and just do it when you're joining:
for x in lst:
print ("".join(str(item) for item in x))