2014-09-11 48 views
1

         该代码块用于显示列表中的随机字符串。我所做的列表是基于对话何时适合使用的类别。例如,有一个问候列表,一个用于告别,并且如下所示:一个用于输入不被理解的时候。在这些列表中,一些字符串使用字符的名称(这是一个变量),其中一些字符串不会。为了给玩家的名字一个使用它的字符串,使用字符串格式是必要的,但是当随机选择的字符串不使用字符串格式时,我得到这个错误:TypeError:并非在字符串格式化过程中转换的所有参数在Python中使用带随机字符串的字符串格式

我怎样才能避免这个错误?异常处理使用想到的,但据我所知不会由于必须适合打印statment,

在“功能”模块工作:

print(random.choice(strings.notUnderstand) % username) 

在“字符串” 模块:

notUnderstand = [ 
"""Pardon? 
""", 
"""I\'m sorry %s, can you repeat that? 
""", 
"""I don\'t understand what you mean by that. 
""" 
] 

回答

0

下面是做到这一点的一种方法:

notUnderstand = [ 
"""Pardon? 
""", 
"""I\'m sorry %(username)s, can you repeat that? 
""", 
"""I don\'t understand what you mean by that. 
""" 
] 

print(random.choice(notUnderstand) % {'username': username}) 
0

可以使用format

import random 

notUnderstand = [ 
"""Pardon? 
""", 
"""I\'m sorry {}, can you repeat that? 
""", 
"""I don\'t understand what you mean by that. 
""" 
] 
username='sundar' 
print random.choice(notUnderstand).format(username) 
1

你可以使用格式,国际海事组织它的清洁:

not_understand = [ 
    """Pardon? 
    """, 
    """I\'m sorry {name}, can you repeat that? 
    """, 
    """I don\'t understand what you mean by that. 
    """ 
] 
print(random.choice(not_understand).format(name='abc')) 
0

我不认为人们真正了解你的问题;这是 - 我怎么能检测一个字符串有一个变量替换,以确保我通过正确数量的参数。

你的问题基本上归结为此。你有两个字符串列表,其中有一个变量代换:

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})) 
+0

虽然你肯定明白我的问题,我不明白你的答案。我忘了提及我对编程和Python很新,所以我不明白什么是元组,什么是替换字典,或者lambda是什么。尽管如此,感谢您的时间和您的回答。 – GG55 2014-09-11 17:19:05