首页 > 解决方案 > 如果长度小于 3,子字符串不会输出任何内容

问题描述

为什么在下面的代码xy没有输出?它仅在子字符串小于 0 时发生:“3”

textString = "You can milk a yak in London Zoo"
print(textString)
a = len(textString) #puts a = 32
b = textString.index('milk') #puts 8 in b
c = textString[11:17] #puts "k a yak" in c
# You could find the positions of the spaces in c
# but this solution assumes they are known
x = c[0:0] #puts “k” in x
y = c[2:2] #puts “a” in y
z = c[4:6] #puts “yak” in z

result = x+y+z
print(x)
print(y)
print(z)
print(result)

标签: python

解决方案


如果您的索引减一 - 第二个数组索引器“最多但不包括”

textString = "You can milk a yak in London Zoo"
print(textString)
a = len(textString) #puts a = 32
b = textString.index('milk') #puts 8 in b
c = textString[11:18] #puts "k a yak" in c
# You could find the positions of the spaces in c
# but this solution assumes they are known
x = c[0:1] #puts “k” in x
y = c[2:3] #puts “a” in y
z = c[4:7] #puts “yak” in z

result = x+y+z
print(x)
print(y)
print(z)
print(result) # -> kayak

推荐阅读