Reputation: 3388
I have a list like this:
la = [3, 7, 8, 9, 50, 100]
I am trying to convert the list into string and add percentage like this:
3%, 7%, 8% and lastly 100%
I doing like this:
str1 = '%, '.join(str(e) for e in sorted_list)
It does the right thing except there's no percentage at last i.e only 100 but I want 100%. How can I do this? Thanks
Upvotes: 1
Views: 85
Reputation: 3300
Yup, it's doing exactly what it's supposed to: putting '%, ' BETWEEN each element. How about simply ...
str1 = '%, '.join(str(e) for e in sorted_list) + '%'
(if sorted_list
can ever be empty, you should handle that case)
Upvotes: 2
Reputation: 198334
la = [3, 7, 8, 9, 50, 100]
(lambda k: ' and lastly '.join([', '.join(k[:-1]), k[-1]]))(["%s%%" % a for a in la])
# '3%, 7%, 8%, 9%, 50% and lastly 100%'
EDIT: small subscripting mistake (then again, as Rohit Jain says... :D )
Upvotes: 1
Reputation: 5122
Thy this:
print map(lambda n: str(n) + '%', [3, 7, 8, 9, 50, 100])
Which creates a list of all of them converted to strings with a percent.
If you still want a string, you can slightly modify it like this:
str1 = ', '.join(map(lambda n: str(n) + '%', [3, 7, 8, 9, 50, 100]))
Upvotes: 1