manbearpig1 manbearpig1 - 1 year ago 71
Python Question

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. Only myString[0] through myString[25] are valid.

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. How can I achieve this?

Answer Source

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.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download