是否有像Lua的string.sub这样的Python函数?

时间:2011-10-06 10:30:40

标签: python string substring

根据标题,我正在寻找类似于Lua的string.sub的Python函数,无论它是第三方还是Python标准库的一部分。我一直在网上搜索(包括stackoverflow)近一个小时,但一直都找不到任何东西。

3 个答案:

答案 0 :(得分:12)

<强>的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'

与Lua不同,Python是零索引,因此字符计数是不同的。数组在Python中以from 1 in Lua,0开始。

在Python切片中,第一个值是包含的,第二个值是独占的(最多但不包括)。空的第一个值等于零,空的第二个值等于字符串的大小。

答案 1 :(得分:10)

Python不需要这样的功能。它的切片语法直接支持String.sub功能(以及更多):

>>> 'hello'[:2]
'he'
>>> 'hello'[-2:]
'lo'
>>> 'abcdefghijklmnop'[::2]
'acegikmo'
>>> 'abcdefghijklmnop'[1::2]
'bdfhjlnp'
>>> 'Reverse this!'[::-1]
'!siht esreveR'

答案 2 :(得分:4)

是的,python提供了一个(在我看来非常好)substring选项:"string"[2:4]返回ri

请注意,此“切片”支持多种选项:

"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)

您会找到有关它的一些信息here