gpt4 book ai didi

python - 将特定字符串放置在特定索引处

转载 作者:行者123 更新时间:2023-11-30 22:38:11 24 4
gpt4 key购买 nike

我想将字符串放置在某个索引处。假设我们从一个空字符串 x="" 开始。然后我想将字母 a、e、i、o 和 u 放在索引 0、2、4、6、8 处,以便得到 x="a e i o u"。然后,也许我想在索引 1,3,5 处添加 z,y,x,以便得到 x=azeyixo u。我怎样才能做到这一点?

最佳答案

你可以制作一个字符串生成器。这是一个开始。

>>> class MutableString:
... def __init__(self, s):
... self._string = s
...
... def __setitem__(self, index, s):
... if index < len(self._string):
... self._string = self._string[:index] + s + \
... self._string[index+len(s):]
... else:
... self._string = self._string + ' ' * \
... (index -len(self._string)) + s
...
... def __str__(self):
... return self._string
...
>>> ms = MutableString("hello world!")
>>> print ms
hello world!
>>> ms[6] = "people"
>>> print ms
hello people
>>> ms = MutableString('')
>>> ms[0] = 'a'; ms[2] = 'e'; ms[4] = 'i'; ms[6] = 'o'; ms[8] = 'u'
>>> print ms
a e i o u
>>> ms[1] = 'z'; ms[3] = 'y'; ms[5] = 'x'
>>> print ms
azeyixo u

或者使用字符列表作为字符串数据的内部表示:

>>> class CharArrayString:
... def __init__(self, s=''):
... self._strdata = [ch for ch in s]
...
... def __setitem__(self, index, s):
... s = [ch for ch in s]
... sd = self._strdata
... if type(index) != slice:
... if index < len(sd):
... sd = sd[:index] + s + sd[index + len(s):]
... else:
... sd = sd + [' '] * (index - len(sd)) + s
... else:
... sd[index] = s
...
... self._strdata = sd
...
... def __getitem__(self, index):
... return ''.join(self._strdata[index])
...
... def __str__(self):
... return ''.join(self._strdata)
...
... def __repr__(self):
... return "ca_str('" + str(self) + "')"
...
... def __add__(self, s):
... if isinstance(s, (CharArrayString, str)):
... return CharArrayString(self._strdata + [ch for ch in s])
... else:
... raise TypeError(f"Catenation operation (+) "
... f"expected another CharArrayString "
... f"or str, but got {type(s)}.")
...

此版本支持前面的用法示例,以及通过 + 进行切片和串联。它并不是字面上的字符数组字符串 - 更像是字符串列表对象。无论如何:

>>> cas = CharArrayString("Hello world!")
>>> cas[::2]
'Hlowrd'
>>> cas[::-1]
'!dlrow olleH'
>>> cas + " Additional text."
ca_str('Hello world! Additional text.')
>>> cas
ca_str('Hello world!')
>>> cas += "Modifying cas."
>>> cas
ca_str('Hello world!Modifying cas.')
>>> cas[3:8] = '12345'
>>> cas
ca_str('Hel12345rld!Modifying cas.')

关于python - 将特定字符串放置在特定索引处,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43672323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com