-3

I find surprising that unlike BASIC python doesn't have .left, .right and .mid methods for strings.

As stated elsewhere it's easy enough to write functions to do the trick but can one add methods to a native class?

So that

a = "Spam" 
b = a.left(3)   
print(b)

would output:

Spa
Austin
  • 25,759
  • 4
  • 25
  • 48
Thot
  • 51
  • 7
  • 1
    Python has slicers, you can use `b = a[0:3]` to achieve the output you want. See https://stackoverflow.com/questions/509211/understanding-slice-notation – Josh21 May 09 '19 at 02:46
  • 1
    you could use something like forbiddenfruit ... but it would be not a good idea at all and quite fragile ... you should just use slicing `a[:3]` is the .left `a[-3:]` is the `.right` youll need to figure out the indexes for middle but it shouldnt be to hard ... basic is not really the gold standard for programming languages – Joran Beasley May 09 '19 at 02:51
  • yes, slicing will do, but I wanted to know if it is possible to add methods to a native class in general. But now I am curious: what is forbiddenfruit? – Thot May 09 '19 at 03:19

2 Answers2

1
b = a[:3]

will take 3 firsts characters of the string

b = a[:15]

will not make an error (not sure on python2)

c = a[-3:]

for the last 3 characters

But you still can override (inherit) string type

class MySuperString(str):
    def left(self, num_char):
        return self[:num_char]

a = MySuperString('plop')
b = a.left(3)

see for example : http://www.nomadiccodemonkey.com/?p=590

edit :

if isinstance(a, str):

won't work anymore, use this instead :

if issubclass(a, str):

or naturally this :

if isinstance(a, MySuperString):

french joke : et ça marche même si tu mets des SuperSlip !

  • Ah, yes! Creating a new class that inherits from the str class is an elegant solution.. Thanks – Thot May 09 '19 at 03:13
0

you can create your own function.

right = lambda str, index: str[-index:]
left = lambda str, index: str[:index]
a = "Spam"
print(left(a,3))
print(right(a,3))
Gaurang Shah
  • 11,764
  • 9
  • 74
  • 137
  • True, but these are functions, I was inquiring about adding methods to the str class. – Thot May 09 '19 at 03:23
  • @Thot you can't add function to existing inbuilt data type as they are written in C. What you can do is create your own `string class` which extends `str`. However, You will have to create a string as .. `name = string("aaa")` – Gaurang Shah May 09 '19 at 16:02