我要做的是将's'作为字符串输入,q作为整数输入。
'x'是一个列表。
s ='abcd'
q = 2
输入x:
0 2
1 3
期望的输出:
abc
bcd
代码:
s=input()
q=int(input())
x=list()
for i in range(q):
x.append(list(map(int,input().split())))
for i,v in enumerate(x):
for j,z in enumerate(v):
print(s[v[i]:v[i+1]])
问题:
我的输出引发错误:索引超出范围
ab
ab
Traceback (most recent call last): File "/home/yash/py/substring.py", line 12, in <module>
print(s[v[i]:v[i+1]]) IndexError: list index out of range:
答案 0 :(得分:0)
一种解决方案可能是:
s = "abcd"
def slicer(string):
return string[int(input("Lower bound (inclusive): ")): \
int(input("Upper bound (inclusive): ")) + 1]
print("Output: {}".format(slicer(s)))
print("Output: {}".format(slicer(s)))
您也可以使用slice()
功能。
s = "abcd"
def slicer(string):
return string[slice(int(input("Lower bound (inclusive): ")), \
int(input("Upper bound (inclusive): ")) + 1)]
print("Output: {}".format(slicer(s)))
print("Output: {}".format(slicer(s)))
这两种情况都会从用户输入的下限返回一个list
切片,包括用户输入的上限。
输出样本:
Lower bound (inclusive): 0
Upper bound (inclusive): 2
Output: abc
Lower bound (inclusive): 1
Upper bound (inclusive): 3
Output: bcd