I have a text file and there are some lines called
moves={123:abc:567:mno}
No I want to convert it in the form
moves={123:abc, 567:mno}
i.e. i want to replace : with , when ':' is after a string and behind a number i.e i want to make it like in a python dictionary format i know how i can change a particular line in the text file like
with open("images/filename.txt", 'r ', encoding='Latin1') as fp:
# read an store all lines into list
lines = fp.readlines()
# move file pointer to the beginning of a file
fp.seek(0)
# truncate the file
fp.truncate()
for line in lines:
if line.startswith('moves='):
do something()
fp.writelines(lines)
I am not being able to figure out how should i replace the line and make it in my desired why. Please don't delete or close the question tell me how i should edit the questionin the comments so i can change it instead. Thanks in advance
CodePudding user response:
If you have a line in your file (as a string) and it's exactly in that format then you can split the string on the colon separators then re-join with a comma in the appropriate place. For example:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(':'.join(t[:2]) ',' ':'.join(t[2:]))
Output:
moves={123:abc,567:mno}
CodePudding user response:
s = 'moves={123:abc:567:mno}'
t = s.split(':')
print(t[2:5])
# print(':'.join(t[:2]) ',' ':'.join(t[2:]))
output = ''
for i in range(int(len(t)/2)):
output = ':'.join(t[i*2:i*2 2]) ', '
output = output.removesuffix(', ')
print(output)
Thanks @Lancelot du Lac to help me improvising your answer I have got the answer to my question