Reputation: 37
Hi I have a list like this: [1,2,3,4,5,6]
I want to add "%"
to all these elements in the list for a result of [1%,2%,3%,4%,5%,6%]
.
I know that I can do it with +"%"
but how can i do it with .format
or another thing?
Upvotes: 0
Views: 4371
Reputation: 2929
Since you've asked: or another thing?
I'll give you another thing
.
Sometimes, you'd desire something, which seems little bad, like this:
# add method to built-in int class to render ints as percents
as_percent = lambda x: str(x) + '%'
# and then monkey patch it
int.as_percent = as_percent
However you'd end up with this Exception
:
TypeError: can't set attributes of built-in/extension type 'int'
But, there is a way..
Before you'd will try the following a little disclaimer:
I've never used this in any actual code, but I find this very fun, and generaly good to know it exists. Having code a little bit in Ruby, I like the idea of monkey patching built-ins. But it is not default behaviour in Python. So, be aware. But at least, try it!
First you need this module forbiddenfruit
(see, the name is quite self-explanatory!). Simply pip
it.
Then it is quite easy. We'll use the exact same lambda
function as_percent
as before.
>>> from forbiddenfruit import curse
>>> # again, do you see the name of the function?!
>>> curse(int, 'as_percent', as_percent)
>>> print((1).as_percent())
1%
>>> [x.as_percent() for x in range(10)]
>>> ['0%', '1%', '2%', '3%', '4%', '5%', '6%', '7%', '8%', '9%']
I've come across it here.
Upvotes: 1
Reputation: 160477
Sure you can do it with format
, your results of course need to be strings:
l = [1,2,3,4,5,6]
r = list(map("{}%".format, l))
now, r
is:
['1%', '2%', '3%', '4%', '5%', '6%']
Alternatively you could do it with a list-comp as in the other answer or, in place, by looping:
for ind, i in enumerate(l):
l[ind] = "{}%".format(i)
Upvotes: 2
Reputation: 3822
This PyFormat help
['{:d}%'.format(elm) for elm in l]
Output :
['1%', '2%', '3%', '4%', '5%', '6%']
Upvotes: 2