4

the problem I'm working on

So I'm creating a 'Aussie' ballot app and I'm looking for a creative solution to an input prompt.

Basically the user inputs how many people, and then submits up to 1000 votes or w/e.

Assuming 3 candidates the input prompt would look something like:

ballot = raw_input('1 for %s: 2 for %s: 3 for %s: ') % (cand_list[0], cand_list[1], cand_list[2])

But what I'd really like to come up with is a dynamic prompt (assume the user enters 5, 10, w/e number of candidates)

I've looked into separating the ballot assignment and printing, or creating a ballot string entirely separate and passing it(assuming I can make some kind of stringbuilder function), but I'm curious to see other approaches. Still tinkering with it to see if I'll need to escape the % formatting.

Python Stringbuilder(sort of) and More string concat

Community
  • 1
  • 1
crownedzero
  • 496
  • 1
  • 7
  • 18

3 Answers3

3

Something like this using string formatting, str.join and enumerate:

>>> candidates = ['foo', 'bar', 'spam']
>>> print ' : '.join('{} for {}'.format(i, c) for i, c in enumerate(candidates, 1))
1 for foo : 2 for bar : 3 for spam

>>> candidates = ['foo', 'bar', 'spam', 'python', 'guido']
>>> print ' : '.join('{} for {}'.format(i, c) for i, c in enumerate(candidates, 1))
1 for foo : 2 for bar : 3 for spam : 4 for python : 5 for guido
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Construct your format string separately in stages:

inner_format_string = "{num} for %s: "
full_format_string = " ".join(inner_format_string.format(num=i) for i in xrange(1, len(cand_list) + 1))

ballot = raw_input(full_format_string % tuple(cand_list))
spencer nelson
  • 4,365
  • 3
  • 24
  • 22
0
canidates = ["Frank","Bill","Joe","Suzy"]
raw_input(", ".join("Enter %d For %s"%(num,canidate) for num,canidate in enumerate(canidates,1)))

perhaps

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179