This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 8 months ago.
The community is reviewing whether to reopen this question as of 11 days ago.
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,
myList.append(munfunc())
How should I convert the returned result to a string in order to join it with the list?
Do I need to do the following for every integer value:
myList.append(str(myfunc()))
Is there a more Pythonic way to solve casting problems?
Calling str(...) is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:
print(','.join(str(x) for x in list_of_ints))
There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like
', '.join(map(str, myList))
The map function in python can be used. It takes two arguments. The first argument is the function which has to be used for each element of the list. The second argument is the iterable.
a = [1, 2, 3]
map(str, a)
['1', '2', '3']
After converting the list into a string you can use the simple join function to combine the list into a single string
a = map(str, a)
''.join(a)
'123'
There are three ways of doing this.
let say you have a list of integers
my_list = [100,200,300]
"-".join(str(n) for n in my_list)
"-".join([str(n) for n in my_list])
"-".join(map(str, my_list))
However as stated in the example of timeit on python website at https://docs.python.org/2/library/timeit.html using a map is faster. So I would recommend you using "-".join(map(str, my_list))
a=[1,2,3]
b=[str(x) for x in a]
print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3]
b=map(str,a)
print b
Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)
For example:
lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]
lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']
As to me, I want to add a str before each str list:
# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']
Or single list:
lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu[5]
How come no-one seems to like repr?
python 3.7.2:
>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>>
Take care though, it's an explicit representation. An example shows:
#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>>
more info at pydocs-repr
Related
a=[2]
a.append(3)
print (a)
result is [2, 3].
I want to have a output 23 instead of [2,3]. Any suggestions?
When you do something like a = [2] in Python, it creates a list out of it with one element 2 in the list.
You seemingly want string operations. There are two ways to do this. Firstly,
a = '2'
a = a + '3'
print (a)
Another way, probably the one which you're looking for, is converting the list into a string, as follows.
a = [2]
a.append(3)
b = ''.join(str(x) for x in a)
print (b)
Here is a brief explanation of the second approach:
You forcibly typecast each element of the list a to string, and then use join method to convert the list to string. Essentially, first the list [2, 3] is converted to ['2', '3'] and then join is used.
Edit:
Another approach, to better explain what I said above,
a = [str(2)]
a.append(str(3))
b = ''.join(a)
print (b)
Since the numbers are stored as ints instead of strings it makes it slightly more difficult as you will need to cast them to strings.
a=[2]
a.append(3)
print("".join(str(x) for x in a))
This will give your desired output. If you want the output to be an int then you can just cast it back.
So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]
I have some problems with the following issue:
I have a string, which contains integers and floats. I fail to extract only the integers (NOT the floats!).
What i have (it is a string):
f= "0:6.0 3:5.6 54:12.3 56:12.0"
How the result should be (not in a string form):
0,3,54,56
I searched on Google (and stack-overflow) which leads to this solution:
[int(s) for s in f.split() if s.isdigit()]
That leads to a empty list.
Other solutions like:
int(re.search(r'\d+', f).group())
Leads to "0 integers". Sorry i'm new but I really can't solve this.
You can use .partition(':'):
>>> s="0:6.0 3:5.6 54:12.3 56:12.0"
>>> [e.partition(':')[0] for e in s.split()]
['0', '3', '54', '56']
Then call int on those strings:
>>> [int(e.partition(':')[0]) for e in s.split()]
[0, 3, 54, 56]
Or,
>>> map(int, (e.partition(':')[0] for e in s.split()))
[0, 3, 54, 56]
And you can use the same method (with a slight change) to get the floats:
>>> map(float, (e.partition(':')[2] for e in s.split()))
[6.0, 5.6, 12.3, 12.0]
Fair question asked in comments: Why use partition ? you can use int(split(":")[0])
With .partition it is clear to all readers (including your future self) that you are looking at 1 split only. (Granted, you could use the 2 argument form of split(delimiter, maxsplit) but I think that is less clear for a single split...)
It is easier to test successful partitioning since partition always produces a three element tuple and you only need to test the truthiness of the element tuple[1].
You can safely use .partion in tuple assignments of the form lh,delimiter,rh=string.partion('delimiter') where lh, rh=string.split('delimiter') will produce a ValueError if the delimiter is not found.
With the delimiter included in the resulting tuple, it is easier to reassemble the original string with ''.join(tuple_from_partion) vs split since the delimiter in split is lost.
Why not?
How about using the following regex:
import re
f = "0:6.0 3:5.6 54:12.3 56:12.0"
answer = [int(x) for x in re.findall(r'\d{1,2}(?=:)', f)]
print(answer)
Output
[0, 3, 54, 56]
You can also achieve the same result using map instead of a list comprehension (as in #dawg's answer):
answer = map(int, re.findall(r'\d{1,2}(?=:)', f))
So I have a list:
['x', 3, 'b']
And I want the output to be:
[x, 3, b]
How can I do this in python?
If I do str(['x', 3, 'b']), I get one with quotes, but I don't want quotes.
In Python 2:
mylist = ['x', 3, 'b']
print '[%s]' % ', '.join(map(str, mylist))
In Python 3 (where print is a builtin function and not a syntax feature anymore):
mylist = ['x', 3, 'b']
print('[%s]' % ', '.join(map(str, mylist)))
Both return:
[x, 3, b]
This is using the map() function to call str for each element of mylist, creating a new list of strings that is then joined into one string with str.join(). Then, the % string formatting operator substitutes the string in instead of %s in "[%s]".
This is simple code, so if you are new you should understand it easily enough.
mylist = ["x", 3, "b"]
for items in mylist:
print(items)
It prints all of them without quotes, like you wanted.
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If you are using Python3:
print('[',end='');print(*L, sep=', ', end='');print(']')
Instead of using map, I'd recommend using a generator expression with the capability of join to accept an iterator:
def get_nice_string(list_or_iterator):
return "[" + ", ".join( str(x) for x in list_or_iterator) + "]"
Here, join is a member function of the string class str. It takes one argument: a list (or iterator) of strings, then returns a new string with all of the elements concatenated by, in this case, ,.
You can delete all unwanted characters from a string using its translate() method with None for the table argument followed by a string containing the character(s) you want removed for its deletechars argument.
lst = ['x', 3, 'b']
print str(lst).translate(None, "'")
# [x, 3, b]
If you're using a version of Python before 2.6, you'll need to use the string module's translate() function instead because the ability to pass None as the table argument wasn't added until Python 2.6. Using it looks like this:
import string
print string.translate(str(lst), None, "'")
Using the string.translate() function will also work in 2.6+, so using it might be preferable.
Here's an interactive session showing some of the steps in #TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)
Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.
>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'
Using .format for string formatting,
mylist = ['x', 3, 'b']
print("[{0}]".format(', '.join(map(str, mylist))))
Output:
[x, 3, b]
Explanation:
map is used to map each element of the list to string type.
The elements are joined together into a string with , as separator.
We use [ and ] in the print statement to show the list braces.
Reference:
.format for string formatting PEP-3101
I was inspired by #AniMenon to write a pythonic more general solution.
mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))
It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format.
For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f
mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))
The output is quite decent:
[1.85, -6.33, 4000.21]
This question already has answers here:
Apply function to each element of a list
(4 answers)
Closed 8 months ago.
The community reviewed whether to reopen this question 16 days ago and left it closed:
Original close reason(s) were not resolved
I need to join a list of items. Many of the items in the list are integer values returned from a function; i.e.,
myList.append(munfunc())
How should I convert the returned result to a string in order to join it with the list?
Do I need to do the following for every integer value:
myList.append(str(myfunc()))
Is there a more Pythonic way to solve casting problems?
Calling str(...) is the Pythonic way to convert something to a string.
You might want to consider why you want a list of strings. You could instead keep it as a list of integers and only convert the integers to strings when you need to display them. For example, if you have a list of integers then you can convert them one by one in a for-loop and join them with ,:
print(','.join(str(x) for x in list_of_ints))
There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like
', '.join(map(str, myList))
The map function in python can be used. It takes two arguments. The first argument is the function which has to be used for each element of the list. The second argument is the iterable.
a = [1, 2, 3]
map(str, a)
['1', '2', '3']
After converting the list into a string you can use the simple join function to combine the list into a single string
a = map(str, a)
''.join(a)
'123'
There are three ways of doing this.
let say you have a list of integers
my_list = [100,200,300]
"-".join(str(n) for n in my_list)
"-".join([str(n) for n in my_list])
"-".join(map(str, my_list))
However as stated in the example of timeit on python website at https://docs.python.org/2/library/timeit.html using a map is faster. So I would recommend you using "-".join(map(str, my_list))
a=[1,2,3]
b=[str(x) for x in a]
print b
above method is the easiest and most general way to convert list into string. another short method is-
a=[1,2,3]
b=map(str,a)
print b
Your problem is rather clear. Perhaps you're looking for extend, to add all elements of another list to an existing list:
>>> x = [1,2]
>>> x.extend([3,4,5])
>>> x
[1, 2, 3, 4, 5]
If you want to convert integers to strings, use str() or string interpolation, possibly combined with a list comprehension, i.e.
>>> x = ['1', '2']
>>> x.extend([str(i) for i in range(3, 6)])
>>> x
['1', '2', '3', '4', '5']
All of this is considered pythonic (ok, a generator expression is even more pythonic but let's stay simple and on topic)
For example:
lst_points = [[313, 262, 470, 482], [551, 254, 697, 449]]
lst_s_points = [" ".join(map(str, lst)) for lst in lst_points]
print lst_s_points
# ['313 262 470 482', '551 254 697 449']
As to me, I want to add a str before each str list:
# here o means class, other four points means coordinate
print ['0 ' + " ".join(map(str, lst)) for lst in lst_points]
# ['0 313 262 470 482', '0 551 254 697 449']
Or single list:
lst = [313, 262, 470, 482]
lst_str = [str(i) for i in lst]
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
lst_str = map(str, lst)
print lst_str, ", ".join(lst_str)
# ['313', '262', '470', '482'], 313, 262, 470, 482
Maybe you do not need numbers as strings, just do:
functaulu = [munfunc(arg) for arg in range(loppu)]
Later if you need it as string you can do it with string or with format string:
print "Vastaus5 = %s" % functaulu[5]
How come no-one seems to like repr?
python 3.7.2:
>>> int_list = [1, 2, 3, 4, 5]
>>> print(repr(int_list))
[1, 2, 3, 4, 5]
>>>
Take care though, it's an explicit representation. An example shows:
#Print repr(object) backwards
>>> print(repr(int_list)[::-1])
]5 ,4 ,3 ,2 ,1[
>>>
more info at pydocs-repr