我刚接触Python,我正在学习我购买的Python课程,他们有一个测验。最后一个问题是打印字符串的最后6个字母。代码如下:
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")然后,输出将是:
The last 6 letters of the welcome message:
'Hello and welcome to the land of Python'
are: Python这是从解决方案中得到的。我不明白这是怎么回事:'{welcome_message[len(welcome_message)-6:]}'
我不明白为什么这个解决方案包含了len()函数。
为什么我不能直接做'{welcome_message[-6:]}?
发布于 2021-05-16 11:30:09
你也会得到同样的输出。在python -1中,索引与最后一个索引相同,如果为空,则表示开始或结束,具体取决于放置索引的位置。例如。
welcome_message[:]将打印整个字符串。
至于你的问题,你可以使用welcome_message[34:],而不是计算你自己,一个更好的写作方式是welcome_message[len(welcome_message)-6:]。但是,更好的编写方式是您指出的解决方案,即welcome_message[-6:]
发布于 2021-05-16 11:30:49
打印(f“欢迎消息的最后6个字母:\n‘{welcome_message}’\n是:'{welcome_messagelen(welcome_message)-6:}'")
welcome_message是一个变量,它可以有无限的字母/字符/数字/符号/字符串等。系统并不直接知道...所以welcome_messagelen...首先找出字符串中有多少个字符,而不是单词...我说字符是因为我们为len()函数提供了welcome_message变量,它只有一个字符串...到目前为止,我希望我已经解释了在{welcome_message[len(welcome_message)]}之前发生了什么,然后它只是len() fn返回的计数的普通老式6算术运算
发布于 2021-05-16 13:42:21
welcome_message = "Hello and welcome to the land of Python"
print(f"The last 6 letters of the welcome message:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")s[i:]它将输出为一个字符串,其中包含从i到string.>d14\n >将输出从索引33到39 index.H215<的字符/code>
记住," "也是字符串中的一个字符。https://stackoverflow.com/questions/67552906
复制相似问题