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

后端 未结 7 1334
再見小時候
再見小時候 2021-01-31 15:11

I want to do something like this:

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

Help!

7条回答
  •  无人及你
    2021-01-31 15:47

    Thanks Andy W

    I found that the mid() did not quite work as I expected and I modified as follows:

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

    I performed the following test:

    print('[1]23', mid('123', 1, 1))
    print('1[2]3', mid('123', 2, 1))
    print('12[3]', mid('123', 3, 1))
    print('[12]3', mid('123', 1, 2))
    print('1[23]', mid('123', 2, 2))
    

    Which resulted in:

    [1]23 1
    1[2]3 2
    12[3] 3
    [12]3 12
    1[23] 23
    

    Which was what I was expecting. The original mid() code produces this:

    [1]23 2
    1[2]3 3
    12[3] 
    [12]3 23
    1[23] 3
    

    But the left() and right() functions work fine. Thank you.

提交回复
热议问题