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

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

2 Comments

why zip range instead of enumerate(canidates,1)?
works great! i'll tinker with getting the newline after the enumeration
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))

Comments

0
canidates = ["Frank","Bill","Joe","Suzy"]
raw_input(", ".join("Enter %d For %s"%(num,canidate) for num,canidate in enumerate(canidates,1)))

perhaps

1 Comment

almost perfect, just have to prevent a new line after each candidate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.