gpt4 book ai didi

python根据字符串位置 move 字符

转载 作者:太空宇宙 更新时间:2023-11-04 10:42:15 24 4
gpt4 key购买 nike

我试图将字符串中的一个特殊字符从一个位置 move 到另一个位置。我希望它出现在下一个角色之后。这是我的字符串:

"th i s. i s. a. n i c ^ e . s t r i ng."

这个符号可以出现在任何时候。我已经能够识别下一个空间,但我仍然无法 move 它。

到目前为止我所做的是:

x= "th i s. i s. a. n i c ^ e . s t r i ng."
for i in range(len(x)):
if x[i] == '^':
j = i + 1
if x[j] == ' ':
j = j + 1
while j < len(x) and x[j] != ' ':
j = j + 1

print "in the position " + str(i) + ", I found a hat: '" + str(x[i]) + "'"
print "in the position " + str(j) + ", I found the next space: '" + str(x[j]) + "'"
x.remove(i)
x.insert('^', j)
else:
print 'somebody help!'

最佳答案

字符串是不可变的,它们没有任何removeinsert 方法。因此,您应该先将字符串转换为列表,然后才能使用 list.removelist.insert

>>> x = "th i s. i s. a. n i c ^ e . s t r i ng."
>>> list(x)
['t', 'h', ' ', 'i', ' ', 's', '.', ' ', 'i', ' ', 's', '.', ' ', 'a', '.', ' ', 'n', ' ', 'i', ' ', 'c', ' ', '^', ' ', 'e', ' ', '.', ' ', 's', ' ', 't', ' ', 'r', ' ', 'i', ' ', 'n', 'g', '.']

最后,在修改列表后,您可以使用 str.join 加入它。

代码中的错误:

 x.remove('^')     # you should remove '^' here, not the index
x.insert(j, '^') # first argument is the index, second is the item

关于python根据字符串位置 move 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19845745/

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