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

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

I want to do something like this:

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

Help!

7条回答
  •  日久生厌
    2021-01-31 15:33

    This is Andy's solution. I just addressed User2357112's concern and gave it meaningful variable names. I'm a Python rookie and preferred these functions.

    def left(aString, howMany):
        if howMany <1:
            return ''
        else:
            return aString[:howMany]
    
    def right(aString, howMany):
        if howMany <1:
            return ''
        else:
            return aString[-howMany:]
    
    def mid(aString, startChar, howMany):
        if howMany < 1:
            return ''
        else:
            return aString[startChar:startChar+howMany]
    

提交回复
热议问题