Baran Aldemir
Baran Aldemir

Reputation: 71

How to switch numbers and characters location in a string in python?

I have file names like this: 13_CL 13_CR 13_TL 13_TR ... and I assigned them to a variable. I need to switch numbers and alphabetical characters in the filenames. the expected result is: CL_13 CR_13 TL_13 TR_13 ...

Upvotes: 0

Views: 126

Answers (5)

The fourth bird
The fourth bird

Reputation: 163457

You might split the value on _ then reverse the array and join back with a _

s="13_CL"
print('_'.join(s.split('_')[::-1]))

Output

CL_13

A regex solution to switch numbers and alphabetical characters could be to capture 1+ digits in group 1 and 1+ chars A-Z in group 2 and in the replacement use the groups in the reversed order.

import re

s="13_CL"
print(re.sub(r"(\d+)_([A-Z]+)", r"\2_\1", s))

Output

CL_13

Upvotes: 2

Cyrille Pontvieux
Cyrille Pontvieux

Reputation: 2471

There are a lots of possibilities here.

One is :

filename_list = ['13_CL', '13_CR', '13_TL', '13_TR']
new_filename_list = ['_'.join(reversed(filename.split('_'))) for filename in filename_list]

split split the string into a list on delimiter

reversed is used to reverse the list order. It produces an iterator which is consumed directly by join without the need to really create a full list object.

join to create a new string from a iterable using a delimiter

Upvotes: 2

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522007

We could use a regex approach here:

filenames = ['13_CL', '13_CR', '13_TL', '13_TR']
output = [re.sub(r'(.*)_(.*)', r'\2_\1', x) for x in filenames]
print(output)  # ['CL_13', 'CR_13', 'TL_13', 'TR_13']

Upvotes: 1

user15801675
user15801675

Reputation:

Try this

str1='13_CL 13_CR 13_TL 13_TR'
str2=' '.join('_'.join(reversed(a.split('_'))) for a in str1.split())
print(str2)

Upvotes: 0

James Bear
James Bear

Reputation: 444

Here is a one line version:

s = ' '.join(['_'.join(reversed(pair.split('_'))) for pair in s.split(' ')])

Upvotes: 0

Related Questions