简体   繁体   English

字符串索引超出范围时如何使字符串索引为圆形

[英]How to make string indices circular when string index out of range

Suppose I have this string: 假设我有这个字符串:

myString = 'abcdefghijklmnopqrstuvwxyz'

If I ask for myString[26], I will get an error saying string index out of range. 如果我要求myString [26],则会收到错误消息,提示字符串索引超出范围。 Only myString[0] through myString[25] are valid. 仅myString [0]至myString [25]有效。

My desired result is to ask for myString[26] and return 'a', because I have overreached the string by 1, and come back around front at 'a' in a circular motion. 我想要的结果是请求myString [26]并返回'a',因为我已经将字符串超出了1,然后以圆周运动在'a'处回到了前面。 How can I achieve this? 我该如何实现?

Use modulo. 使用模。

myString = 'abcdefghijklmnopqrstuvwxyz'

def access_char(string, i):
    return string[i % len(string)]

print(access_char(myString, 57))
# >>> f

This will also work for any other sequence datatype (list, tuple, etc.) 这也适用于任何其他序列数据类型(列表,元组等)

You just need to do myString[<index> % len(myString)] . 您只需要执行myString[<index> % len(myString)] <index> would be any integer that will be an index. <index>是将成为索引的任何整数。

For example: 例如:

myString[26 % len(myString)]
>>> 'a'

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

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