-1

Why do x and y have no output in the code below? It only happens when the substring is less than 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)
quamrana
  • 37,849
  • 12
  • 53
  • 71
KURTZ
  • 1

2 Answers2

3

Your indexing if off by one - the second array indexer is 'up to but not including'

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
Will Jenkins
  • 9,507
  • 1
  • 27
  • 46
0
x = c[0] #puts “k” in x
y = c[2] #puts “a” in y
KURTZ
  • 1
  • 1
    If you want to use exclusively substrings, you can use `c[0:1]` and `c[2:3]`. Either way, the output you currently obtain is "kaya" because, for the same reason as above, `c[4:6]` only gets two characters, and should be replaced with `c[4:7]` or `c[4:]` – Adalcar Mar 01 '21 at 16:22