Python替换字符而不使用替换方法

时间:2017-08-17 14:37:07

标签: python

我正在尝试使用Python运行以下脚本:

test_string = "Hallo"

test_string[0] = "T"

我收到以下错误:

  

' STR'对象不支持项目分配

现在我知道你可以使用Python的replace default函数,但是有没有其他方法可以在不使用标准python函数的情况下实现上述功能?

感谢,

6 个答案:

答案 0 :(得分:4)

这有效:

test_string = "Hallo"
# turn the string into a list
test_string  = list(test_string)
# change the character you want  
test_string[0] = "T"
# convert the list back to a string. 
test_string = "".join(test_string)

答案 1 :(得分:2)

字符串是不可变的,因此如果您不想转换为可变类型,则必须创建一个新字符串。以下是一个示例函数:

def replace_(original_string, replace_string, index):
    return original_string[:index] + replace_string + original_string[index + len(replace_string):]

print(replace_("Hallo", "T", 0))
print(replace_("Hallo", "Te", 0))

输出:

Tallo
Tello

我想注意我更喜欢转换为列表的答案;这个答案只提供纯字符串实现。

答案 2 :(得分:1)

所以你想改变字符串的第一个字母?

你可以做到

t = "T" + t[1:len(t)]

注意:我已经把" t"而不是" test_string"

答案 3 :(得分:0)

使用列表推导和枚举类似

"".join(['T' if i == 0 else x for i, x in enumerate(test_string) ])

也有效

答案 4 :(得分:0)

这是使用bytearray的另一种解决方案,它比MedAli的解决方案快一点:

test_string = "Hello"
b = bytearray(test_string)  # Or Python3 bytearray(test_string, 'utf-8')
b[0] = ord('T')
str(b)

答案 5 :(得分:0)

奇怪的是,没有人做过明显的......

test_string = "T" + test_string[1:]