开发者

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

开发者 https://www.devze.com 2023-04-11 08:00 出处:网络
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 ( includin

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 an开发者_高级运维d 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'


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消