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

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

I want to do something like this:

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

Help!

相关标签:
7条回答
  • 2021-01-31 15:57

    These work great for reading left / right "n" characters from a string, but, at least with BBC BASIC, the LEFT$() and RIGHT$() functions allowed you to change the left / right "n" characters too...

    E.g.:

    10 a$="00000"
    20 RIGHT$(a$,3)="ABC"
    30 PRINT a$
    

    Would produce:

    00ABC
    

    Edit : Since writing this, I've come up with my own solution...

    def left(s, amount = 1, substring = ""):
        if (substring == ""):
            return s[:amount]
        else:
            if (len(substring) > amount):
                substring = substring[:amount]
            return substring + s[:-amount]
    
    def right(s, amount = 1, substring = ""):
        if (substring == ""):
            return s[-amount:]
        else:
            if (len(substring) > amount):
                substring = substring[:amount]
            return s[:-amount] + substring
    

    To return n characters you'd call

    substring = left(string,<n>)
    

    Where defaults to 1 if not supplied. The same is true for right()

    To change the left or right n characters of a string you'd call

    newstring = left(string,<n>,substring)
    

    This would take the first n characters of substring and overwrite the first n characters of string, returning the result in newstring. The same works for right().

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