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.
Asked
Active
Viewed 617 times
5
-
2What does `string.sub` do in Lua? – John Keyes Oct 06 '11 at 10:33
-
Did you try: http://tinyurl.com/dyes5s – Constantinius Oct 06 '11 at 10:34
-
@JohnKeyes: string.sub returns a string that has been cut from another, example: str = "Hello, World!" print( string.sub(str,1,5) ) Would output: Hello – Erkling Oct 06 '11 at 11:58
3 Answers
13
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.
10
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'

Marcelo Cantos
- 181,030
- 38
- 327
- 365
-
Thank you very much. :) Btw, I'm just playing with it in the interpreter here.. and 'hello'[0:4] only gives me 'hell', but surely if the string begins at 0 then 4 would be the last character? – Erkling Oct 06 '11 at 10:39
-
1@Erkling: Slicing is inclusive on the first argument, but exclusive on the second. a[0:4] gives you elements 0 to 3. – Marcelo Cantos Oct 06 '11 at 10:41
-
The equivalent in function calls, if you need those instead, is: 'hello'.__getitem__(slice(1,None)) or import operator; getitem('hello', slice(1,None)) – WaffleSouffle Oct 06 '11 at 10:42
5
Yes, python offers a (in my opinion very nice) substring option: "string"[2:4]
returns ri
.
Note that this "slicing" supports a variety of options:
"string"[2:] # "ring"
"string"[:4] # "stri"
"string"[:-1] # "strin" (everything but the last character)
"string"[:] # "string" (captures all)
"string"[0:6:2] # "srn" (take only every second character)
"string"[::-1] # "gnirts" (all with step -1 => backwards)
You'll find some information about it here.

vladimir vojtisek
- 141
- 1
- 8

phimuemue
- 34,669
- 9
- 84
- 115