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

Question:

I want to do something like this:

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

Help!

Asked By: pythonprogrammer

||

Answers:

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

Answered By: frnhr

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]
Answered By: Andy W

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().

Answered By: Gareth Lock

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.

Answered By: Stanton Attree

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

Answered By: user6474469

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]
Answered By: Jim Sullivan

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
Answered By: Scott

Based on the comments above, it would seem that the Right() function could be refactored to handle errors better. This seems to work:

def right(s, amount):
    if s == None:
        return None
    elif amount == None:
        return None # Or throw a missing argument error
    s = str(s)
    if amount > len(s):
        return s
    elif amount == 0:
        return ""
    else:
        return s[-amount:]

print(right("egg",2))
print(right(None, 2))
print(right("egg", None))
print(right("egg", 5))
print("a" + right("egg", 0) + "b")
Answered By: Simon Kingaby
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.