Python Forum
changing characters in multiple strings in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
changing characters in multiple strings in a list
#1
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
Reply
#2
>>> "CT-0921-0001".replace('921', '08')
'CT-008-0001'
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
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)
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read module/class from list of strings? popular_dog 1 424 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Trying to understand strings and lists of strings Konstantin23 2 698 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 647 Jul-19-2023, 06:46 PM
Last Post: deanhystad
  xml indent SubElements (wrapping) with multiple strings ctrldan 2 1,382 Jun-09-2023, 08:42 PM
Last Post: ctrldan
  Delete strings from a list to create a new only number list Dvdscot 8 1,466 May-01-2023, 09:06 PM
Last Post: deanhystad
  Help with Logical error processing List of strings dmc8300 3 1,031 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  Splitting strings in list of strings jesse68 3 1,702 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Search multiple CSV files for a string or strings cubangt 7 7,842 Feb-23-2022, 12:53 AM
Last Post: Pedroski55
  How to combine multiple rows of strings into one using pandas? shantanu97 1 3,098 Aug-22-2021, 05:26 AM
Last Post: klllmmm
  Why changing data in a copied list changes the original list? plumberpy 3 2,190 Aug-14-2021, 02:26 AM
Last Post: plumberpy

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020