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

PythonBasic

Python Problem Overview


I want to do something like this:

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

Help!

Python Solutions


Solution 1 - Python

slices to the rescue :)

Solution 2 - Python

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 - Python

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 - Python

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

Solution 5 - Python

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]

Solution 6 - Python

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

Solution 7 - Python

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

Solution 8 - Python

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")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpythonprogrammerView Question on Stackoverflow
Solution 1 - PythonAndy WView Answer on Stackoverflow
Solution 2 - PythonfrnhrView Answer on Stackoverflow
Solution 3 - PythonStanton AttreeView Answer on Stackoverflow
Solution 4 - Pythonuser6474469View Answer on Stackoverflow
Solution 5 - PythonJim SullivanView Answer on Stackoverflow
Solution 6 - PythonGareth LockView Answer on Stackoverflow
Solution 7 - PythonScottView Answer on Stackoverflow
Solution 8 - PythonSimon KingabyView Answer on Stackoverflow