Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用随机字符串的字符串格式_Python_String Formatting - Fatal编程技术网

在Python中使用随机字符串的字符串格式

在Python中使用随机字符串的字符串格式,python,string-formatting,Python,String Formatting,这段代码用于显示列表中的随机字符串。我列出的列表是根据对话适合使用的时间进行分类的。例如,有一个问候列表,一个用于道别,如下所示:一个用于输入不理解时。在这些列表中,有些字符串使用字符的名称(这是一个变量),有些则不使用。为了给使用它的字符串指定播放器的名称,必须使用字符串格式,但是当随机选择的字符串不使用字符串格式时,我会遇到以下错误:TypeError:在字符串格式设置过程中,并非所有参数都被转换 我怎样才能避免这个错误呢?我想到了使用异常处理,但据我所知,由于必须符合打印状态,因此无法使用

这段代码用于显示列表中的随机字符串。我列出的列表是根据对话适合使用的时间进行分类的。例如,有一个问候列表,一个用于道别,如下所示:一个用于输入不理解时。在这些列表中,有些字符串使用字符的名称(这是一个变量),有些则不使用。为了给使用它的字符串指定播放器的名称,必须使用字符串格式,但是当随机选择的字符串不使用字符串格式时,我会遇到以下错误:TypeError:在字符串格式设置过程中,并非所有参数都被转换

我怎样才能避免这个错误呢?我想到了使用异常处理,但据我所知,由于必须符合打印状态,因此无法使用

在“功能”模块中:

在“字符串”模块中:


以下是一种方法:

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

您可以使用
格式

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)

您可以使用格式,因为它更干净:

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

我不认为人们真的理解你的问题;这就是-如何检测字符串有变量替换,以确保传入正确数量的参数

你的问题基本上就是这个。您有一个包含两个字符串的列表,其中一个具有变量替换:

s = ['Hello {}', 'Thank You']
需要随机打印其中一个字符串。如果它有一个变量,而您没有传入它,它将无法正确打印(它将引发
TypeError

但是,如果字符串中确实有占位符,则必须传递足够的变量来替换所有占位符,否则将得到一个
索引器

>>> print('hello {name} {}'.format(name=1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
接下来,创建一个替换字典:

subs = {'name': lambda: 'hello', 'foo': lambda: '42'}
我在这里使用lambdas是因为实际上您希望调用某个函数来获取变量的值

现在,当您要构建字符串时:

random_string, vars = ('Hello {name}', ('name',))
print(random_string.format(**{k:subs.get(k)() for k in vars}))

虽然你肯定明白我的问题,但我不明白你的答案。我忘了提到我对编程和Python相当陌生,所以我不理解元组是什么,替换字典到底是什么,或者lambadas是什么。尽管如此,谢谢你的时间和回答。
>>> print('hello'.format(name=1))
hello
>>> 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'}
random_string, vars = ('Hello {name}', ('name',))
print(random_string.format(**{k:subs.get(k)() for k in vars}))