gpt4 book ai didi

python - 使用许多用户的输入创建一个字符串

转载 作者:行者123 更新时间:2023-12-02 03:52:24 24 4
gpt4 key购买 nike

我正在开发一个需要用户输入大量信息的程序,

如果他写的是/end,程序就会结束并用他的输入打印一个字符串。我还补充说,如果用户的字符串以疑问词开头,它会自动在字符串中添加一个问号。

现在,我的问题是我不知道如何将所有字符串放在一起,我只尝试过 append 但它不起作用。

程序:

def stringCreator(mySTR):
capitalized = mySTR.capitalize()
questions = ('what', 'how', 'can', 'why')
if mySTR.startswith(questions):
return '{}?'.format(capitalized)
else:
return '{}.'.format(capitalized)


result = # What should I use there ?
while True:
userInput = input('Say something: ')
if userInput == '/end':
break
else:
# Connect all string together with result


print(' '.join(stringCreator(result)))

编辑:

Wolph的帮助下,我得到了这个结果。

首先,我用result变量创建了一个列表,其次,我添加了else条件result.append(userInput) ,

然后我更改了 print 函数

print(' '.join(stringCreator(result)))print(stringCreator(''.join(result)))

最终计划:

def stringCreator(mySTR):
capitalized = mySTR.capitalize()
questions = ('what', 'how', 'can', 'why')
if mySTR.startswith(questions):
return '{}?'.format(capitalized)
else:
return '{}.'.format(capitalized)


result = []
while True:
userInput = input('Say something: ')
if userInput == '/end':
break
else:
result.append(userInput)


print(stringCreator(' '.join(result)))

最佳答案

这里有很多选项。可能效率最低但最简单的方法是直接附加到字符串:

result = ''
...
result += userInput # optionally + '\n'

更好的方法是附加到列表并稍后加入:

result = []
...
result.append(userInput)
...
result = ' '.join(result) # or '\n'

最好的方法可能是使用更专业的数据结构,例如 collections.deque使附加更加有效:

from collections import deque
...
result = deque()
...

deque的接口(interface)很像列表,但它不能非常有效地进行直接索引。

关于python - 使用许多用户的输入创建一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59479820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com