Home > Mobile >  Move substring to front of string
Move substring to front of string

Time:11-02

I have a field "Numbers" that can have a value such as:

"01-02-03-04-Zero"

I want to change the substring "Zero" to "00" and move it to the front of the string, so that the result is:

"00-01-02-03-04"

Not all rows contain this "Zero" substring so I only want to perform this on fields that do.

CodePudding user response:

You can use regex. In this approach you can replace Zero with 00 if exist.

import re

def change_Zero(st):
    # If we find '-Zero', we replace all strings with '00' that add to the first part. 
    # with '\1' access to first part
    return re.sub(r"(.*)(-Zero)", r"00-\1", st) 

print(change_Zero("01-02-03-04-Zero"))
print(change_Zero("01-02-03-04-05"))

Output:

00-01-02-03-04
01-02-03-04-05

CodePudding user response:

One way to do it is to split the string to a list, find the indexes where "Zero" is, remove them, and add to "00" to the front of the list. Finally joint the list back to a string.

s = "01-02-03-04-Zero"
s_split = s.split("-")
zero_idxs = [n for n, elem in enumerate(s_split) if elem == "Zero"]

for idx in zero_idxs:
    s_split.pop(idx)

s = "-".join(["00"] * len(zero_idxs)   s_split)

This solution will work for any number of "Zero"s in the string.

  • Related