Python Forum
changing characters in multiple strings in a list - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: changing characters in multiple strings in a list (/thread-8495.html)



changing characters in multiple strings in a list - newmanf - Feb-22-2018

Well I've tried many things and I can't seem to find a way to change strings or file names in a list such as:

CT-0921-0001
CT-0921-0002
CT-0922-0003
.
.
.

TO new file names

CT-008-0001
CT-008-0002
CT-008-0003
.
.
.

Any help is greatly appreciated. Thanks ahead of time


RE: changing characters in multiple strings in a list - wavic - Feb-23-2018

>>> "CT-0921-0001".replace('921', '08')
'CT-008-0001'



RE: changing characters in multiple strings in a list - kannanv110 - Feb-23-2018

Below code will work well for whatever in between "-"
#!/usr/bin/python
import glob
from __future__ import print_function

for fileName in glob.glob('CT-*'):
        fileName = fileName.split('-')
        fileName[1] = '008'
        fileName = '-'.join(fileName)
        print(fileName)



RE: changing characters in multiple strings in a list - newmanf - Feb-23-2018

Thank you. I was looking at glob function. It printed the new names very nicely but I actually need the names in the directory to be changed. So I am looking at os.rename(fileName, fileName.replace ...). Not sure how to make it change the names in the directory.