0

I have a set of files, in folders that I want to rename. The format is:

lesson1
lesson2
.....
lesson11
lesson99
lesson100
lesson130   

When I sort in Windows, the order is my string, so is not correct(example):

lesson1 
lesson100

I want to become (rename):

_001_lesson
_010_lesson

How do I catch/split the numbering part at the end from the string 'lesson' ?

also a more complex case when the string is not fixed(as lesson):

title abc1
title def2
title acr 3 
user3541631
  • 3,686
  • 8
  • 48
  • 115
  • 1
    What happens if you had something like: `lesson1_part5_2018` or similar? – Jon Clements Sep 18 '18 at 11:33
  • I don't have that situation, only the lesson number at the end, but if your solution can cover other cases also, it is great – user3541631 Sep 18 '18 at 11:34
  • 1
    Have you seen: https://stackoverflow.com/questions/4836710/does-python-have-a-built-in-function-for-string-natural-sort ? – Jon Clements Sep 18 '18 at 11:35
  • 1
    You can extract numbers from a string using `''.join([i for i in l if i.isdigit()])` where l is the string. Combine this with a for loop to iterate through your names – Ninad Gaikwad Sep 18 '18 at 11:36
  • @JonClements I will try natsort, even if my thought was to extract the number, and rename the file, not sorting – user3541631 Sep 18 '18 at 11:42
  • In those answers there's also examples of how to extract numbers from strings... once you've done that - you can rename the file if you want... In fact - Leopold's answered with just that :) – Jon Clements Sep 18 '18 at 11:56

2 Answers2

2

What I would suggest is the following, using python's re module

import re

def rename(old_name):
  # Run a Regex to find the ending number
  match = re.search('lesson(\d+)', old_name)

  # If that was a match (that should be necessary, but 
  # checking input is always a good idea)
  if match:
    # Retrieves the id and converts it to an integer
    id = int(match.group(1))

    # Gets the formatted name out
    return '_{:03d}_lesson'.format(id)

  return None

This is quite modular. You can change the regex next time you want to parse similar file names :).

Léopold Houdin
  • 1,515
  • 13
  • 18
1

For the fixed string, you can use the split method:

Number = "lesson123".split("lesson")[1] # "123"
Title  = "lesson123".split(Number)[0]   # "lesson"

For _001_lesson you can write something like this, assuming you need N extra zeros in front of the number.

New_name = "_" + N*"0" + "%d_%s" %(Number, Title)

For your other example, I understand you want to grab all the characters after "title"?

Number = "title acr 3".split("title")[1] # " acr 3"
Title = "title acr 3".split(Number)[0]   # "title"

If you are annoyed by those extra spaces you can remove them using strip or replace:

Clean_number = Number.strip(" ")
# or
Clean_number = Number.replace(" ", "")
Guimoute
  • 4,407
  • 3
  • 12
  • 28