提问人:Heather Hepburn 提问时间:7/7/2023 最后编辑:Constantin HongHeather Hepburn 更新时间:7/8/2023 访问量:69
我不明白为什么这是“语法错误”?
I don't understand why this is a "syntax error"?
问:
我正在尝试列出将从中随机选择的消息。我一直收到语法错误,我试图弄清楚我错过了什么?
我看了一下代码,什么也看不到,但我觉得有些我不知道,我尝试了在线检查器,但他们只是说错误,没有告诉我错误是什么......
messageRnd = ['Countdown time!'(days_left)'','OMG! '(dayt_left)'days to go!!', 'Just a reminder, there are'(days_left)' days to go!', ' '(days_left)'days left!', 'T-'(days_left)' to takeoff.', 'did you know there are '(days_left) 'days until we takeoff?']
答:
1赞
Inofearu
7/7/2023
#1
from random import randint
while True:
days_left = str(randint(0,100))
messageRnd = ['Countdown time! ' + (days_left),
'OMG! ' + (days_left) + ' days to go!!',
'Just a reminder, there are ' + (days_left) + ' days to go!',
(days_left) + ' days left!',
'T-' + (days_left) + ' to takeoff.',
'Did you know there are ' + (days_left) + ' days until we takeoff?']
print(messageRnd[randint(0,len(messageRnd) - 1)].replace("days_left", days_left))
你不能只把变量名放进去,你需要一个或来连接。在这里,您需要使用,因为该变量将被视为列表中的单独条目。,
+
+
如果您想在字符串中包含许多变量,最好使用 f 字符串,因为它更易于键入和阅读。
这允许您拥有一个更具可读性的列表,但代价是如果发生更改,则必须重新定义它:days_left
from random import randint
while True:
days_left = str(randint(0,100))
messageRnd = [f'Countdown time! {days_left}',
f'OMG! {days_left} days to go!!',
f'Just a reminder, there are {days_left} days to go!',
f'{days_left} days left!',
f'T-{days_left} to takeoff.',
f'Did you know there are {days_left} days until we take off?']
print(messageRnd[randint(0,len(messageRnd) - 1)])
正如 Cmd858 在评论中所说,您还可以执行以下操作,以避免在具有可读性优势的同时重新定义列表:
from random import randint
messageRnd = ['Countdown time! days_left',
'OMG! days_left days to go!!',
'Just a reminder, there are days_left days to go!',
'days_left days left!',
'T-days_left to takeoff.',
'Did you know there are days_left days until we take off?']
while True:
days_left = str(randint(0,100))
print(messageRnd[randint(0,len(messageRnd) - 1)].replace("days_left", days_left))
评论
0赞
Cmd858
7/8/2023
这里需要注意的一点是,如果 的值发生了变化,则必须再次创建列表,这并不是真正的问题,但可能并不理想。days_left
评论
'Countdown time!'(days_left)''
'Countdown time!"(days_left)"'
days_left
'(days_left)'
'Countdown time!'days_left