Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Python function like Lua's string.sub?

As per the title, I am looking for a Python function similar to Lua's string.sub, whether it be 3rd party or part of the Python Standard library. I've been searching all over the internet ( including stackoverflow ) for nearly an hour and haven't been able to find anything whatsoever.

like image 665
Erkling Avatar asked Oct 06 '11 10:10

Erkling


2 Answers

Lua:

> = string.sub("Hello Lua user", 7)      -- from character 7 until the end
Lua user
> = string.sub("Hello Lua user", 7, 9)   -- from character 7 until and including 9
Lua
> = string.sub("Hello Lua user", -8)     -- 8 from the end until the end
Lua user
> = string.sub("Hello Lua user", -8, 9)  -- 8 from the end until 9 from the start
Lua
> = string.sub("Hello Lua user", -8, -6) -- 8 from the end until 6 from the end
Lua

Python:

>>> "Hello Lua user"[6:]
'Lua user'
>>> "Hello Lua user"[6:9]
'Lua'
>>> "Hello Lua user"[-8:]
'Lua user'
>>> "Hello Lua user"[-8:9]
'Lua'
>>> "Hello Lua user"[-8:-5]
'Lua'

Python, unlike Lua, is zero index, hence the character counting is different. Arrays start from 1 in Lua, 0 in Python.

In Python slicing, the first value is inclusive and the second value is exclusive (up-to but not including). Empty first value is equal to zero, empty second value is equal to the size of the string.

like image 59
Jin Avatar answered Sep 19 '22 15:09

Jin


Python doesn't require such a function. It's slicing syntax supports String.sub functionality (and more) directly:

>>> 'hello'[:2]
'he'
>>> 'hello'[-2:]
'lo'
>>> 'abcdefghijklmnop'[::2]
'acegikmo'
>>> 'abcdefghijklmnop'[1::2]
'bdfhjlnp'
>>> 'Reverse this!'[::-1]
'!siht esreveR'
like image 36
Marcelo Cantos Avatar answered Sep 18 '22 15:09

Marcelo Cantos