Home > Software design >  Python best way to 'swap' words (multiple characters) in a string?
Python best way to 'swap' words (multiple characters) in a string?

Time:12-03

Consider following examples:

string_now = 'apple and avocado'
stringthen = string_now.swap('apple', 'avocado') # stringthen = 'avocado and apple'

&

string_now = 'fffffeeeeeddffee'
stringthen = string_now.swap('fffff', 'eeeee') # stringthen = 'eeeeefffffddffee'

Approaches discussed in enter image description here

A chain of replace() methods is not only far from ideal but because of sequantial nature, it will not translate things perfectly as

string_now = 'apple and avocado'
stringthen = string_now.replace('apple','avocado').replace('avocado','apple')

gives 'apple and apple' instead of 'avocado and apple'.

So whats the best way to achieve this?

CodePudding user response:

Given that we want to swap words x and y, and that we don't care about the situation where they overlap, we can:

  • split the string on occurrences of x
  • within each piece, replace y with x
  • join the pieces with y

Essentially, we use split points within the string as a temporary marker to avoid the problem with sequential replacements.

Thus:

def swap_words(s, x, y):
    return y.join(part.replace(y, x) for part in s.split(x))

Test it:

>>> swap_words('apples and avocados and avocados and apples', 'apples', 'avocados')
'avocados and apples and apples and avocados'
>>>

CodePudding user response:

I managed to make this function that does exactly what you want.

def swapwords(mystr, firstword, secondword):
    splitstr = mystr.split(" ")

    for i in range(len(splitstr)):
        if splitstr[i] == firstword:
            splitstr[i] = secondword
            i =1
        if splitstr[i] == secondword:
            splitstr[i] = firstword
            i =1

    newstr = " ".join(splitstr)

   return newstr

Basically, what this does is it takes in your string "Apples and Avacados", and splits it by spaces. Thus, each word gets indexed in an array splitstr[]. Using this, we can use a for loop to swap the words. The i =1 is in order to ensure the words don't get swapped twice. Lastly, I join the string back using newstr= " ".join(splitstr) which joins the words separated by a space.

Running the following code gives us: Avacados and Apples.

CodePudding user response:

I can’t think of any method other than to create a new string, iterate through the original string and append each character to the new string - but checking for the string to swap at the end of the new string every iteration, and swap if it matches.

  • Related