繁体   English   中英

Python 的新手。 有人可以向我解释这行代码吗?

[英]New to Python. Can someone explain this line of code to me?

所以我是 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:]}'")

output 将是:

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() function。

为什么我不能只做'{welcome_message[-6:]} '?

你也会得到同样的 output 。 在 python -1 索引与最后一个索引相同,当它为空白时,它表示开始或结束,具体取决于您放置它的位置。 例如。

welcome_message[:]

将打印整个字符串。

至于您的问题,您可以使用welcome_message[34:] ,而不是计算自己更好的写作方式是welcome_message[len(welcome_message)-6:] 但是更好的写作方式是您指出的解决方案,即welcome_message[-6:]

print(f"欢迎信息的最后 6 个字母:\n'{welcome_message}'\nare: '{welcome_message[len(welcome_message)-6:]}'")

这是发生了什么welcome_message是一个变量,它可以有无限的字母/字符/数字/符号/字符串等。系统不知道第一手...所以welcome_message[len...]首先找到有多少个字符在字符串中,而不是单词...我说字符是因为我们提供了len() function 和只有 1 个字符串的 welcome_message 变量...所以到目前为止我希望我解释了直到{welcome_message[len(welcome_message)]}然后它只是简单的旧 -6 算术运算,来自len() fn 返回的计数

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:]}'")
  1. 这里welcome_message 存储了一个字符串,它是“Hello and Welcome to the Land of Python”。
  2. 在打印时,如果我们将\n添加到字符串中,它将 output 换行作为答案。
  3. len(welcome_message)-6 = 39-6 = 33。
  4. 在字符串切片s[i:]中,它将 output 作为一个字符串,其中包括从i到字符串末尾的字符。
  5. 因此welcome_message[len(welcome_message)-6:]将 output 索引从第 33 到第 39 的字符。
  6. 请记住, " "也是字符串的一个字符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM