-2

My folder contains .jpg files in folder. I need to fetch only the characters from the file names.

I removed all the non alphabets but it resulted in a single string without spaces

Input: Boston_terrier_02303.jpg Desired Output: Boston terrier

rjgupta21
  • 182
  • 4
  • 17

1 Answers1

2

Assuming that you always have the same structure (n word fragments, 1 number, and the output), you can simply get your desired result by:

new_string = " ".join(string.split("_")[:-1])

To elaborate: You start by splitting the strings at the underscores, and then selecting everything but the last. Then simply join the remaining strings with a space between them.

dennlinger
  • 9,890
  • 1
  • 42
  • 63
  • And filename extension? – bipll Jun 21 '18 at 05:44
  • since you are splitting at the underscores, the ".jpg" will also be part of the last element in the list; since we are dropping that, we are also dropping the ".jpg" – dennlinger Jun 21 '18 at 05:45
  • Yes, that's my point, but OP hasn't clearly formulated what he's trying to achieve. – bipll Jun 21 '18 at 05:48
  • why? He clearly specified the desired output, which consists of only the name of the dog breed. – dennlinger Jun 21 '18 at 05:53
  • @dennlinger thank you so much. That was just it. And the `[:-1]` removes doesn't include the last `_` and thus removes the part after it. Correct? – rjgupta21 Jun 21 '18 at 07:19
  • @bipll I just need the name of the dog breed without any extension and numbers. Thank you for your insight. :) – rjgupta21 Jun 21 '18 at 07:20
  • Yes. The `.split("_")` implicitly removes any `_` from your filenames anyways, so it's not included. And the `[:-1]` is basically a selector of "everything but the last element". Please consider accepting the answer if it should fit your desired result. – dennlinger Jun 21 '18 at 08:01
  • @dennlinger Sure. Thanks again. :) – rjgupta21 Jun 21 '18 at 15:23