我不认为人们真正了解你的问题;这是 - 我怎么能检测一个字符串有一个变量替换,以确保我通过正确数量的参数。
你的问题基本上归结为此。你有两个字符串列表,其中有一个变量代换:
s = ['Hello {}', 'Thank You']
随机的,需要打印这些字符串之一。如果有一个变量,你不通过它,它不会正确打印(这将提高TypeError
)
>>> print('hello %s' % (1,))
hello 1
>>> print('hello' % (1,))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
可以部分地通过使用.format()
摆脱这个问题的,因为它会悄无声息当没有占位符,它取代失败:
>>> print('hello'.format(name=1))
hello
但是,如果你的字符串确实有占位符,你必须通过足够的变量来代替所有的占位符,否则你会得到一个IndexError
:
>>> print('hello {name} {}'.format(name=1))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
要解决此问题,您必须跟踪每个字符串中有多少个变量,以确保您传递的参数数量正确。
s = [('Hello {name}',('name',)), ('{name} is {foo}', ('name','foo',))]
接下来,创建一个替代词典::
subs = {'name': lambda: 'hello', 'foo': lambda: '42'}
通过存储在列表中的元组,其具有数(以及可选地,可变的种类)的字符串需要为此我在这里使用lambda表达式,因为实际上你会想要调用一些函数来获取变量的值。
现在,当你想建立自己的字符串:
random_string, vars = ('Hello {name}', ('name',))
print(random_string.format(**{k:subs.get(k)() for k in vars}))
虽然你肯定明白我的问题,我不明白你的答案。我忘了提及我对编程和Python很新,所以我不明白什么是元组,什么是替换字典,或者lambda是什么。尽管如此,感谢您的时间和您的回答。 – GG55 2014-09-11 17:19:05