Python: Is there an equivalent of mid, right, and left from BASIC?

pythonprogrammer picture pythonprogrammer · Mar 23, 2014 · Viewed 228.8k times · Source

I want to do something like this:

    >>> mystring = "foo"
    >>> print(mid(mystring))

Help!

Answer

Andy W picture Andy W · Mar 23, 2014

slices to the rescue :)

def left(s, amount):
    return s[:amount]

def right(s, amount):
    return s[-amount:]

def mid(s, offset, amount):
    return s[offset:offset+amount]