Home > Blockchain >  Conditionally replace substring in a string
Conditionally replace substring in a string

Time:06-09

I have a string that looks like-

str1="lol-tion haha-futures-tion yo-tion ard-tion pomo-tion"

I want to replace the substring tion with cloud IF it has only 1 - between lol and tion lol-tion

str2=str1.replace('tion','cloud')

But when the word has two - like instancehaha-futures-tion I want to replace it like below-

str3=str1.replace('tion','')

Expecting output-> haha-futures

How can I accomplish both these conditional replacements?

CodePudding user response:

You can try this code with regex and condition,

import re
str1="lol-tion haha-futures-tion yo-tion ard-tion pomo-tion"
str2=""
for sub_string in str1.split(' '):
    if re.search(r'^[a-z,-] -tion$', sub_string):
        if re.match(r"[a-zA-Z] [-][a-zA-Z] -tion$",sub_string):
            print("match")
            sub_string=sub_string.replace('tion','')
        else:
            sub_string=sub_string.replace('tion','cloud')
        print(sub_string)
    str2 =sub_string " "
print(str2)

CodePudding user response:

Your description isn't really clear, nor does it fully specify what should happen in all cases, but here's one interpretation:

def replace_tion(word):
    replacements = {1: 'cloud', 2: ''}
    replacement = replacements.get(word.count('-'), 'tion')
    return word.replace('tion', replacement)

str1 = "lol-tion haha-futures-tion yo-tion ard-tion pomo-tion"
tions_replaced = ' '.join(replace_tion(word) for word in str1.split(' '))

# 'lol-cloud haha-futures- yo-cloud ard-cloud pomo-cloud'

CodePudding user response:

IIUC this will work:

new_str1 = ' '.join([string.strip('-tion') 
                     if string.count('-')==2 
                     else string.replace('tion','cloud') 
                     for string in str1.split(' ')])
print(new_str1)

'lol-cloud haha-futures yo-cloud ard-cloud pomo-cloud'
  • Related