字符串运算混乱? 5级

时间:2019-03-01 16:12:07

标签: python-3.x

我是python的新手,我不知道为什么这段代码会给我这个输出。我尝试搜索周围的答案,但找不到任何内容,因为我不确定要搜索的内容。

非常喜欢一个类似解释的解释,我为5

astring = "hello world"
print(astring[3:7:2])

这给了我:“ l”

astring = "hello world"
print(astring[3:7:3])

给我:“ lw”

我不能为之困惑。

2 个答案:

答案 0 :(得分:1)

我有种感觉,您对此有点复杂。 由于字符串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)

这样,它对人类用户来说更容易阅读,并且可以减轻您的错误。

答案 1 :(得分:0)

这是python中的字符串切片。 切片类似于常规的字符串索引,但是它可以返回字符串的一部分。

在切片中使用两个参数,例如[a:b]将返回一个字符串,从索引a开始,直到但不包括索引b。 例如:

"abcdefg"[2:6]将返回"cdef"

使用三个参数执行类似的功能,但是切片将仅在选定的间隙之后返回字符。例如[2:6:2]将返回第二个从索引2开始到索引5的字符。 即"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中切割和切片字符串的更详细的解释。