有没有类似Lua的Python函数字符串.sub?

2024-05-19 03:23:44 发布

您现在位置:Python中文网/ 问答频道 /正文

根据标题,我正在寻找一个类似Lua的Python函数字符串.sub,无论它是第三方还是python标准库的一部分。我在互联网上搜索了将近一个小时(包括stackoverflow),但什么也没找到。在


Tags: 函数字符串标题标准互联网stackoverflowlua小时
3条回答

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:

^{pr2}$

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

在Python切片中,第一个值为inclusive,第二个值为exclusive(直到但不包括)。空的第一个值等于零,空的第二个值等于字符串的大小。在

Python不需要这样的函数。它的切片语法支持字符串.sub功能(及更多)直接:

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

是的,python提供了一个(在我看来非常好的)子字符串选项:"string"[2:4]返回{}。在

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

"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。在

相关问题 更多 >

    热门问题