简体   繁体   English

字符串索引超出范围Python

[英]String index out of range Python

Trying to write a code at the moment that basically tests to see if the letter that lies at r (so here (2,3)) is equal to a particular letter or string. 试着写一个代码,基本上测试看看位于r的字母(所以这里(2,3))是否等于特定的字母或字符串。

def test():

txt = "test.txt"
r = (2,3)
if txt[r[0]][r[1]] == 'l':
    return (True)
elif txt[r[0]][c[1]] == "m":
    return (False)
elif txt[r[0]][c[1]] == "b":
    return (True)

But i keep getting an error. 但我不断收到错误。 The error dialogue is this: 错误对话是这样的:

if txt[r[0]][r[1]] == 'l':
IndexError: string index out of range

I have no idea what im doing wrong considering i had it working earlier today. 考虑到我今天早些时候工作,我不知道我做错了什么。 Also, before you ask, i have to code it this way for a particular reason. 此外,在您提出要求之前,我必须以特殊原因对此进行编码。

Thanks. 谢谢。

Please note, 请注意,

if txt[r[0]][r[1]] == 'l':

should be written as 应该写成

if txt[r[0]:r[1]] == 'l':

and similarly other usage should be changed 同样应该改变其他用法

What are you trying to do? 你想做什么? What would your return be? 你的回报是什么?

The reason it doesn't work is this: 它不起作用的原因是:

r = (2,3)
txt[r[0]][r[1]] -> txt[2][3]

txt[2] == 's'
s[3] -> IndexError

As mentioned by @Abhijit, if you are trying to grab the character by doing a slice, then 正如@Abhijit所提到的,如果你试图通过切片来抓住角色,那么

txt[r[0]:r[1]] is correct.

However, if you are always doing a slice that grabs one character, meaning your r tuple is always of the form (N, N+1), like (2, 3), then you may want to change your strategy. 但是,如果你总是做一个抓取一个角色的切片,这意味着你的r元组总是具有(N,N + 1)形式,如(2,3),那么你可能想要改变你的策略。

Note that for your given example you could do: 请注意,对于您给出的示例,您可以:

if any([letter in txt for letter in ['l', 'b']]):
    return True

If you need to check for actual slices in the text and not just a single character, then the above will still work. 如果您需要检查文本中的实际切片而不仅仅是单个字符,那么上述内容仍然有用。

if any([letter_group in txt for letter_group in ['te', 'st']]):
    return True

or even: 甚至:

if any([letter in txt for letter in 'lb']]):
    return True

for example... 例如...

You don't need to do a slice to check if a character is present at a certain location. 您无需执行切片来检查某个位置是否存在某个字符。 For example: 例如:

txt = 'test.txt'
if txt[2] == 's':
    print 'runs'

So if you coordinate is (2, 3) then you only need to use the first value: 因此,如果你的坐标是(2, 3)那么你只需要使用第一个值:

txt = 'test.txt'
coord = (2, 3)
if txt[coord[0]] == 's':
    print 'runs'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM