Python: Is there an equivalent of mid, right, and left from BASIC?
279,282
Solution 1
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]
Solution 2
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
Solution 3
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.
Solution 4
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]
Author by
pythonprogrammer
Updated on July 09, 2022Comments
-
pythonprogrammer almost 2 years
I want to do something like this:
>>> mystring = "foo" >>> print(mid(mystring))
Help!
-
user2357112 about 10 yearsCareful with that
right
function.'asdf'[-0:] == 'asdf'
, not''
. -
Andy W about 10 years@user2357112 sure, you are correct. The code was provided rather for illustartive purpose to show how the functions in Python and Basic might correspond
-
Bowdzone almost 9 yearsThis 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.
-
user96931 almost 5 yearsDon't forget: left() and right() may return an error if
amount
is>
than the amount of characters ins
. -
user96931 almost 5 yearsThe
mid()
function has to be replaced by the answer below. -
Caltor almost 4 years
right
andleft
in basic return a portion of the string, not a boolean.