1

德尔福有功能

  • Insert(将子字符串 Str2 插入到字符串 Str 的偏移量 P 处)和
  • Delete(从偏移量 P 处的字符串 Str 中删除 N 个字符)。

它们在 Python 中的字符串类比是什么?

4

2 回答 2

2

Python 字符串是不可变的,因此您无法修改现有字符串——但您可以将这些操作应用于字符串并生成一个新字符串。

可能最好的方法是slicing,这是索引语法的扩展,允许您提取多个字符。所以:

>>> 'abcde'[1:4]
'bcd'

请注意,第一个索引是包含的,但第二个索引是排除的。起初这很奇怪,但它是 Python 中普遍存在的约定。

如果省略第一个或最后一个索引,则切片将分别转到字符串的开头或结尾:

>>> 'abcde'[1:]
'bcde'
>>> 'abcde'[:4]
'abcd'

最后,您可以使用+运算符进行字符串连接:

>>> 'abc' + 'de'
'abcde'

将所有这些部分放在一起,您可以根据需要插入和删除子字符串:

>>> s = 'abcde'
>>> s[:2] + 'XYZ' + s[2:]  # Insert 'XYZ' before index 2
'abXYZcde'
>>> s[:2] + s[4:]          # Delete indices from 2 to before 4
'abe'

如果您想要insertdelete按照您所描述的那样发挥作用,您将自己编写它们——但这并不难。剧透警告——在阅读下面的代码之前,您可能想自己尝试一下。:)

def insert(str, str2, p):
    return str[:p] + str2 + str[p:]

def delete(str, p, n):
    return str[:p] + str[p + n:]

(您可能会想出更好的参数名称——特别是,使用str是不可取的,因为它也是 Python 内置的名称——但对于这个例子,我故意使用了你在问题中使用的相同名称。)

于 2013-07-14T20:14:46.997 回答
2

您可以使用

  • s1[:p] + s2 + s1[p:]
  • s1[:p] + s1[p+n:]

例如:

>>> s1 = 'hello world'
>>> s2 = 'xyz'
>>> p = 3
>>> s1[:p] + s2 + s1[p:]
'helxyzlo world'
>>> n = 2
>>> s1[:p] + s1[p+n:]
'hel world'
于 2013-07-14T20:09:42.570 回答