Python中的动态连接字符串创建

时间:2013-11-08 18:12:51

标签: python string loops

the problem I'm working on

所以我正在创建一个'澳洲'选票应用程序,我正在寻找输入提示的创意解决方案。

基本上用户输入了多少人,然后提交多达1000票或w / e。

假设3个候选人输入提示符如下:

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

但我真正想要的是动态提示(假设用户输入5,10,w / e个候选人)

我已经研究过将选票分配和打印分开,或者创建一个完全独立并传递它的选票字符串(假设我可以制作某种字符串构建器功能),但我很想看到其他方法。仍然在修补它,看看我是否需要逃避%格式化。

Python Stringbuilder(sort of)More string concat

3 个答案:

答案 0 :(得分:2)

使用字符串格式str.joinenumerate

这样的内容
>>> 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

答案 1 :(得分:0)

分阶段构建格式字符串:

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))

答案 2 :(得分:0)

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

也许

相关问题