1

例如, my String = 'xx22xx_1x_xxxx-xxxx',x可以是任何字母。现在我想删除前两个位置的字母xx和第七个位置1,以便得到一个NewString = '22xx_x_xxxx-xxxx'. 有什么功能可以擦除特定位置的字母吗?

4

2 回答 2

5

你想实现切片!它不仅适用于字符串。

此问题的示例:Is there a way to substring a string in Python?

>>> x = "Hello World!"
>>> x[2:]
'llo World!'
>>> x[:2]
'He'
>>> x[:-2]
'Hello Worl'
>>> x[-2:]
'd!'
>>> x[2:-2]
'llo Worl'

要回答您的问题,请执行此操作!

删除前两个“xx”

NewString = String[2:]

删除 1

NewString = NewString[:5]+NewString[7:]
于 2013-07-23T20:30:53.200 回答
3

这将做到:

def erase(string, positions):
    return "".join([y for x,y in enumerate(string) if x not in positions])

演示:

>>> s='xx22xx_1x_xxxx-xxxx'
>>> erase(s, (0,1,7))
'22xx_x_xxxx-xxxx'
>>>
于 2013-07-23T20:40:56.197 回答