python根据字符串位置 move 字符

标签 python string position character move

我试图将字符串中的一个特殊字符从一个位置 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/

相关文章:

python - 元组元素在列表中的位置

python - 当变量在别处发生变化时如何更新类的列表或字典?

c++ - c_str 函数有什么用?

javascript - 如何实现toString将数字转换为字符串?

Android 查找当前位置错误

css - react native :Styles overriding each other and container goes out of position

python - 自定义 Django 字段来存储电子邮件地址列表

python - 如何使用 rtree、python 查找查询框(查询区域)内的最近点

java - 将 HashMap 的键和值连接到列表

html - 如何将图像放在嵌入式 YouTube iframe 后面