Split string and join in multiple combination python

Viewed 160

I have a folder name as = "2545 S3C 5005 P1 5007 P2 5009 P3"

The pattern is that there would be 3 files inside this folder which would be named as:

  1. "2545 S3C 5005 P1"
  2. "2545 S3C 5007 P2"
  3. "2545 S3C 5009 P3"

I want to create the names of the files from the folder name and thus i want to split the name of the folder and the join that in combinations to form the file names.

The code i have tried so far is:


folder = "2545 S3C 5005 P1 5007 P2 5009 P3"

i=iter(Folder.split(' '))
File1 = map("-".join,zip(*[i]*4))

This joins in the first 4 words in the split list but I am not sure how to make the other combinations. Please help.

Thanks

4 Answers

You may try a combination of splitting along with re.findall:

folder = "2545 S3C 5005 P1 5007 P2 5009 P3"
prefix = ' '.join(folder.split()[:2])
output = [prefix + ' ' + x for x in re.findall(r'\b\d+ P\d+', folder)]
print(output)  # ['2545 S3C 5005 P1', '2545 S3C 5007 P2', '2545 S3C 5009 P3']

This will do the trick using f-strings considering the format you have mentioned:

import re

folder = "2545 S3C 5005 P1 5007 P2 5009 P3"
folder_split = folder.split()
file_prefix = ' '.join(folder_split[:2])
output = [f"{file_prefix} {' '.join(file_name_remaining)}" for file_name_remaining in zip(folder_split[2::2], folder_split[3::2])]
print(output)

Actually, for your use case, a simple split and join should be sufficient:

folder = "2545 S3C 5005 P1 5007 P2 5009 P3"
splitted = folder.split()
paths = [' '.join(splitted[:2])+ ' '.join(splitted[i:i+2]) for i in range(2, len(splitted), 2)]

OUTPUT:

paths

['2545 S3C5005 P1', '2545 S3C5007 P2', '2545 S3C5009 P3']

One option is to use generator expressions. This particular version assumes it's always a set of 3 files:

folder = "2545 S3C 5005 P1 5007 P2 5009 P3"
subs = iter(folder.split())
prefix = next(subs) + ' ' + next(subs) + ' '
output = [prefix + next(subs) + ' ' + next(subs) for _ in '123']
output
['2545 S3C 5005 P1', '2545 S3C 5007 P2', '2545 S3C 5009 P3']

For a more general case where the number of entries can vary:

folder = "2545 S3C 5005 P1 5007 P2 5009 P3 5022 P4"
words = folder.split()
subs = iter(words)
prefix = next(subs) + ' ' + next(subs) + ' '
output = [prefix + next(subs) + ' ' + next(subs) for _ in range((len(words) - 2)//2)]
output
['2545 S3C 5005 P1',
 '2545 S3C 5007 P2',
 '2545 S3C 5009 P3',
 '2545 S3C 5022 P4']
Related