user1881957
user1881957

Reputation: 3388

Can't seem to add percentage at last in this list?

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

Answers (5)

raton
raton

Reputation: 428

python 3.2
str1 = ','.join(str(e)+"%" for e in sorted_list)

Upvotes: 0

CodeBoy
CodeBoy

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

Amadan
Amadan

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

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798746

', '.join('%d%%' % (x,) for x in la)

Upvotes: 5

jackcogdill
jackcogdill

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

Related Questions