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

8

69

I want to do something like this:

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

Help!

Merchandise answered 23/3, 2014 at 2:20 Comment(3)
What does mid in BASIC do?Godrich
I suspect mid, left and right require additional arguments, right?Unburden
They do require additional parameters in BASIC. Two for Left and Right, and either two or three for MidMesser
V
133

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]
Vaclav answered 23/3, 2014 at 2:29 Comment(4)
Careful with that right function. 'asdf'[-0:] == 'asdf', not ''.Railroader
@Railroader sure, you are correct. The code was provided rather for illustartive purpose to show how the functions in Python and Basic might correspondVaclav
Don't forget: left() and right() may return an error if amount is > than the amount of characters in s.Lethargic
The mid() function has to be replaced by the answer below.Lethargic
D
37

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

Detonation answered 23/3, 2014 at 2:28 Comment(0)
C
11

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.

Coulometer answered 11/12, 2016 at 14:34 Comment(0)
F
5

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

Fallible answered 5/2, 2018 at 6:27 Comment(1)
I get [1, 2, 3, 4] as the output for print(thadari[:-2])Faerie
P
2

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]
Pollock answered 25/4, 2018 at 18:26 Comment(0)
M
1

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
Michaeline answered 18/4, 2019 at 20:49 Comment(1)
right and left in basic return a portion of the string, not a boolean.Loge
T
0

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

Tonsure answered 27/5, 2015 at 11:16 Comment(1)
This is really a comment, not an answer. With a bit more rep, you will be able to post comments. Please use answers only for posting actual answers.Haro
C
0

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")
Catharine answered 21/3, 2021 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.