我正在尝试有条件地更新从指定位置开始的字符串的一部分。我有这样的东西:
i = 0
bre = 'newtext'
with open(myfile, "r") as f:
data = f.readlines()
for line in data:
if i > 0 and line[98] == '1':
print 'ok'
line[1562] = bre
i += 1
# write line to a file
我收到的错误是:
Traceback (most recent call last):
File "test.py", line 19, in <module>
line[1562] = bre
您正在尝试将字符串中的字符元素更改为另一个字符串
line = line[:1562] + bre + line[1563:]
# to skip the length of your bre
line = line[:1562] + bre + line[(1562+len(bre)):]
示例
bre = 'newtext'
myString = "asdfghjkl"
#replace character at index 2 with my string bre
myString = myString [:2]+ bre+ myString [3:]
print(myString)
asnewtextfghjkl
字符串也不像列表一样可变
您无法转到索引并更改字符
示例
s = "abc"
a[1] = 'z' # is wrong because 'str' object does not support item assignment
s = a[:1] + 'z' + a[2:] #but this will work
# this takes the pointer s and points it a completely new string
有趣的事实:这就是您可以在字典中使用字符串作为键而不是列表的原因。字符串可以散列
您在问题中提供的上下文太少,无法给您完整的答案,但是我发现您的代码存在一个主要问题:您试图分配给str
对象,但是str
是不可变的。
如果您已经报告了完整的追溯,您会发现类似以下内容:
TypeError:'str'对象不支持项目分配
因此,您必须从已有的字符串开始创建新的字符串,例如:
s = 'I like dogs more than mice!'
t = 'cat'
n = 7
u = s[:n] + t + s[n + len(t):]
print(u)
# I like cats more than mice!
在python中,字符串是不可变的。此外,当您执行line[1562] = bre
时,您尝试将一个字符串(bre
)分配给另一个字符(line[1562]
)。幸运的是,在python中解决该问题非常简单。这样做的一个好方法是将所有先前的line
字符串与bre
以及之后的line
字符串连接在一起。最后,您将其分配给var line
。有点像
line = line[:1562] + bre + line[1563:]
但是请注意,执行此操作时,data
对象内的行不会更改。您只是在更改它的副本。如果要读取文件行然后将其写到文件中更改,则需要执行类似操作
i = 0
bre = 'newtext'
with open(myfile, "r") as f:
data = f.readlines()
for x,line in enumerate(data):
if i > 0 and line[98] == '1':
print 'ok'
data[x] = line[:1562] + bre + line[1563:]
i += 1
with open(new_file, 'w') as f
for line in data:
f.write(data)