我不明白为什么这是“语法错误”?

I don't understand why this is a "syntax error"?

提问人:Heather Hepburn 提问时间:7/7/2023 最后编辑:Constantin HongHeather Hepburn 更新时间:7/8/2023 访问量:69

问:

我正在尝试列出将从中随机选择的消息。我一直收到语法错误,我试图弄清楚我错过了什么?

我看了一下代码,什么也看不到,但我觉得有些我不知道,我尝试了在线检查器,但他们只是说错误,没有告诉我错误是什么......

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?']
python 语法 语法错误

评论

4赞 G. Anderson 7/7/2023
你的引号到处都是。请记住,在 python 中,要打印的内部引号的样式必须与表示字符串的引号不同。也许应该是?'Countdown time!'(days_left)'''Countdown time!"(days_left)"'
0赞 G. Anderson 7/7/2023
此外,如果您希望在字符串中实际包含变量而不是字符串文字,则可能值得一看此问题和答案days_left'(days_left)'
1赞 Constantin Hong 7/7/2023
此外,请尝试在 IDE 中使用语法高亮显示。
2赞 Sarah Messer 7/7/2023
第一个可能打算成为列表元素的元素被破坏了,可能还有其他的也被破坏了。你不能简单地通过左引号和右引号来连接python字符串,即使是语法错误。请参阅 w3schools.com/python/gloss_python_string_concatenation.asp 了解如何执行此操作'Countdown time!'days_left
0赞 Heather Hepburn 7/7/2023
我将发布整个代码,因为现在它只是发布(days_left)而不是我想要的数字。

答:

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