Erk*_*ing 5 python string substring
根据标题,我正在寻找类似于Lua的string.sub的Python函数,无论它是第三方还是Python标准库的一部分.我一直在网上搜索(包括stackoverflow)近一个小时,但一直都找不到任何东西.
Jin*_*Jin 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
Run Code Online (Sandbox Code Playgroud)
蟒蛇:
>>> "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'
Run Code Online (Sandbox Code Playgroud)
与Lua不同,Python是零索引,因此字符计数是不同的.数组从Lua中的1开始,在Python中从 0 开始.
在Python切片中,第一个值是包含的,第二个值是独占的(最多但不包括).空的第一个值等于零,空的第二个值等于字符串的大小.
Mar*_*tos 10
Python不需要这样的功能.它的切片语法直接支持String.sub功能(以及更多):
>>> 'hello'[:2]
'he'
>>> 'hello'[-2:]
'lo'
>>> 'abcdefghijklmnop'[::2]
'acegikmo'
>>> 'abcdefghijklmnop'[1::2]
'bdfhjlnp'
>>> 'Reverse this!'[::-1]
'!siht esreveR'
Run Code Online (Sandbox Code Playgroud)
是的,python 提供了一个(在我看来非常好的)子字符串选项:"string"[2:4]returns 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)
Run Code Online (Sandbox Code Playgroud)
您可以在这里找到一些相关信息。