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
1
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 "-"
1
2
3
4
5
6
7
8
9
#!/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
  question about changing the string value of a list element jacksfrustration 4 2,179 Feb-08-2025, 07:43 AM
Last Post: jacksfrustration
  (Fix it) Extend list with multiple other ones andreimotin 3 823 Aug-12-2024, 07:48 PM
Last Post: Pedroski55
  How to read module/class from list of strings? popular_dog 1 1,355 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  Trying to understand strings and lists of strings Konstantin23 2 1,819 Aug-06-2023, 11:42 AM
Last Post: deanhystad
  problem in using int() with a list of strings akbarza 4 1,886 Jul-19-2023, 06:46 PM
Last Post: deanhystad
  xml indent SubElements (wrapping) with multiple strings ctrldan 2 3,252 Jun-09-2023, 08:42 PM
Last Post: ctrldan
  Delete strings from a list to create a new only number list Dvdscot 8 3,436 May-01-2023, 09:06 PM
Last Post: deanhystad
  Help with Logical error processing List of strings dmc8300 3 1,908 Nov-27-2022, 04:10 PM
Last Post: Larz60+
  Splitting strings in list of strings jesse68 3 2,629 Mar-02-2022, 05:15 PM
Last Post: DeaD_EyE
  Search multiple CSV files for a string or strings cubangt 7 13,365 Feb-23-2022, 12:53 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

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