Chaban33
Chaban33

Reputation: 1382

Take one part of the string and swtich places with other

I have this

string = "Kabale (Blue/Purple 841, 34)"

and I want to switch what is inside braces places

so my desired result would be

string = "Kabale (34, Blue/Purple 841)"

how can i do it.

string can be diffirent like "Vesta1 (Brown Stripes 227, 34)" or

"Vincenta (Black 837, 34)"

but pattern is the same

Upvotes: 1

Views: 30

Answers (1)

Eduardo Coltri
Eduardo Coltri

Reputation: 506

You can use this custom function

def reverse_partition(string):
    first_parentheses = string.find('(')
    last_parentheses = string.find(')')
    target = string[first_parentheses+1:last_parentheses]
    target_split_by_comma = target.split(',')
    target_split_by_comma.reverse()
    return string.replace(target,', '.join(target_split_by_comma).strip())

Upvotes: 2

Related Questions