Issue
I'm trying to conditionally update part of a string starting at a specified location. I have something like this:
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
The error I am receiving is:
Traceback (most recent call last):
File "test.py", line 19, in <module>
line[1562] = bre
Solution
You are trying to change an element of a string which is character to another string
line = line[:1562] + bre + line[1563:]
# to skip the length of your bre
line = line[:1562] + bre + line[(1562+len(bre)):]
example
bre = 'newtext'
myString = "asdfghjkl"
#replace character at index 2 with my string bre
myString = myString [:2]+ bre+ myString [3:]
print(myString)
asnewtextfghjkl
also string is not mutable like a list
you cannot go to an index and change the character
example
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
FUN FACT: that is the reason you can use string as a key in a dictionary but not a list. strings can be hashed
Answered By - Kuldeep Singh Sidhu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.