Reputation: 157
I know that this function moves around characters in a string, as such:
def swapping(a, b, c):
x = list(a)
x[b], x[c] = x[c], x[b]
return ''.join(x)
Which allows me to do this:
swapping('abcde', 1, 3)
'adcbe'
swapping('abcde', 0, 1)
'bacde'
But how can I get it to do something like this, so I'm not just moving around letters? This is what I want to accomplish:
swapping("Boys and girls left the school.", "boys", "girls")
swapping("Boys and girls left the school.", "GIRLS", "bOYS")
should both have an output: "GIRLS and BOYS left the school."
# Basically swapping the words that are typed out after writing down a string
Upvotes: 2
Views: 696
Reputation: 1723
You can do something like this:
def swap(word_string, word1, word2):
words = word_string.split()
try:
idx1 = words.index(word1)
idx2 = words.index(word2)
words[idx1], words[idx2] = words[idx2],words[idx1]
except ValueError:
pass
return ' '.join(words)
Upvotes: 3
Reputation: 140196
with regular expressions and a replacement function (could be done with lambda
and a double ternary but that's not really readable)
Matches all the words (\w+
) and compares against both words (case-insensitive). If found, return the "opposite" word.
import re
def swapping(a,b,c):
def matchfunc(m):
g = m.group(1).lower()
if g == c.lower():
return b.upper()
elif g == b.lower():
return c.upper()
else:
return m.group(1)
return re.sub("(\w+)",matchfunc,a)
print(swapping("Boys and girls left the school.", "boys", "girls"))
print(swapping("Boys and girls left the school.", "GIRLS", "bOYS"))
both print: GIRLS and BOYS left the school.
Upvotes: 2
Reputation: 22314
You want to do two separate things here: swapping and changing character case.
The former has been addressed in other answers.
The later can be done by searching words in a case insensitive manner, but replacing with the input words, keeping cases.
def swapping(word_string, word1, word2):
# Get list of lowercase words
lower_words = word_string.lower().split()
try:
# Get case insensitive index of words
idx1 = lower_words.index(word1.lower())
idx2 = lower_words.index(word2.lower())
except ValueError:
# Return the same string if a word was not found
return word_string
# Replace words with the input words, keeping case
words = word_string.split()
words[idx1], words[idx2] = word2, word1
return ' '.join(words)
swapping("Boys and girls left the school.", "GIRLS", "BOYS")
# Output: 'GIRLS and BOYS left the school.'
Upvotes: 0
Reputation: 379
Use split
function to get a list of words separated by whitespaces
def swapping(a, b, c):
x = a.split(" ")
x[b], x[c] = x[c], x[b]
return ' '.join(x)
If you want to pass strings as parameters use .index()
to get index of the strings that you want to swap.
def swapping(a, b, c):
x = a.split(" ")
index_1 = x.index(b)
index_2 = x.index(c)
x[index_2], x[index_1] = x[index_1], x[index_2]
return ' '.join(x)
Upvotes: 2