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.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With