我是python的新手,我不知道为什么这段代码会给我这样的输出。我试着到处寻找答案,但什么也找不到,因为我不确定要搜索什么。
如果你能给我解释一下,我会很感激的
astring = "hello world"
print(astring[3:7:2])这给了我:"l“
也是
astring = "hello world"
print(astring[3:7:3])给我:"lw“
我不能理解为什么。
发布于 2019-03-02 00:53:47
这是python中的字符串切片。分片类似于常规的字符串索引,但它只能返回字符串的一部分。
在一个切片中使用两个参数,比如[a:b],将返回一个字符串,从索引a开始直到索引b为止。例如:
"abcdefg"[2:6]将返回"cdef"
使用三个参数执行类似的功能,但是切片将只返回所选间隙之后的字符。例如,[2:6:2]将返回从索引2开始直到索引5的每隔一秒的字符。ie "abcdefg"[2:6:2]将返回ce,因为它只计算每隔一秒的字符数。
在您的示例astring[3:7:3]中,切片从索引3(第二个l)开始,并将指定的3个字符(第三个参数)向前移动到w。然后它在索引7处停止,返回lw。
实际上,当只使用两个参数时,第三个参数缺省为1,因此astring[2:5]与astring[2:5:1]相同。
Python Central对python中的剪切和切分字符串有更详细的解释。
发布于 2019-03-02 00:57:16
我有一种感觉,你已经把这件事稍微复杂化了。由于字符串astring是静态设置的,因此您可以更轻松地执行以下操作:
# Sets the characters for the letters in the consistency of the word
letter-one = "h"
letter-two = "e"
letter-three = "l"
letter-four = "l"
letter-six = "o"
letter-7 = " "
letter-8 = "w"
letter-9 = "o"
letter-10 = "r"
letter11 = "l"
lettertwelve = "d"
# Tells the python which of the character letters that you want to have on the print screen
print(letter-three + letter-7 + letter-three)通过这种方式,人类用户可以更容易地阅读,并且可以减少您的错误。
https://stackoverflow.com/questions/54948388
复制相似问题