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

后端 未结 7 1335
再見小時候
再見小時候 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]
    
    0 讨论(0)
  • 2021-01-31 15:35

    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]
    
    0 讨论(0)
  • 2021-01-31 15:35

    There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

    str = "this_is_a_test"
    left = str.startswith("this")
    print(left)
    > True
    
    right = str.endswith("test")
    print(right)
    > True
    
    0 讨论(0)
  • 2021-01-31 15:40

    You can use this method also it will act like that

    thadari=[1,2,3,4,5,6]
    
    #Front Two(Left)
    print(thadari[:2])
    [1,2]
    
    #Last Two(Right)# edited
    print(thadari[-2:])
    [5,6]
    
    #mid
    mid = len(thadari) //2
    
    lefthalf = thadari[:mid]
    [1,2,3]
    righthalf = thadari[mid:]
    [4,5,6]
    

    Hope it will help

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-31 15:50

    If I remember my QBasic, right, left and mid do something like this:

    >>> s = '123456789'
    >>> s[-2:]
    '89'
    >>> s[:2]
    '12'
    >>> s[4:6]
    '56'
    

    http://www.angelfire.com/scifi/nightcode/prglang/qbasic/function/strings/left_right.html

    0 讨论(0)
提交回复
热议问题