0

I was wondering how to reverse two characters in a string. Here are some examples:

'wing' => 'iwng', 'inwg', 'ingw'

'west' => 'ewst', 'eswt', 'estw'

I was going to use any answers given and put it in a while loop so I can get all the possible combinations of a string while swapping two characters at a time. ex.

counter = 0

while (counter <= len(str1)):
    if str1 == reverse(str2):
      return str2
    elif str1 == str2
       return str2
    else:
      str1 = *some code that would swap the the characters m and n*
      str1 =  
      n += 1
      m += 1
return False

This code compares two strings, str1 to str2, and checks to see if they are the same by swapping the characters around.

ALSO, is there a way i can get this to produce a list of the results instead of printing them?

THANKS!

3
  • how did you get from west to eswt by swapping two characters? Commented Mar 18, 2012 at 0:36
  • Define "swap". Is this homework? Commented Mar 18, 2012 at 0:46
  • you swap two characters side by side while going through the string. so swap [0] and [1] then [1] [2], then [2] [3], etc. Commented Mar 18, 2012 at 0:47

3 Answers 3

2

Try this:

s = 'wing'
s = 'west'
l = [x for x in s]
for i in xrange(len(s)-1):
    l[i], l[i+1] = l[i+1], l[i]
    print "".join(l)
Sign up to request clarification or add additional context in comments.

2 Comments

ok, awesome! that is beautiful! instead of printing it, i just want the result of each loop iteration, i an just append the ''.join(l) to a locally defined variable?
It's just l = list(s), no need for the list comprehension.
1

In order to generate all possibilities, we can use:

s = "yourstring"
for i in range(0,len(s)-2):
    if i>0: print s[:i]+s[i+1:i-1:-1]+s[i+2:]
    else: print s[1]+s[0]+s[2:]

Comments

1

Since you wish to actually compare two strings to see if they "are the same by swapping two characters around," you do not actually need to generate all possible combinations, instead you can iterate through each of the characters in each of the strings and ensure that no more than two of them are not equal.

This can be done as follows:

def twoCharactersDifferent(str1,str2):
    if sorted(str1) != sorted(str2): #they must contain the same letters, exactly!
        return False    
    numDifferent = 0    
    for i in range(len(str1)):

        numDifferent += (str1[i] != str2[i])
        if numDifferent >2:
            return False
    return True

print twoCharactersDifferent('wings','winxg')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.