Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Function to accept a string and swap pairs of characters
- # Mike Kerry - Feb 2021 - acclivity2@gmail.com
- # Examples
- # "hello world" becomes "ehll oowlrd"
- # "behave now" becomes "ebahevn wo"
- def swap_pairs(s1): # Define a function to do the work. "s1" contains the string to be processed
- # We cannot directly change the input string, because strings in Python are "immutable" (cannot be modified)
- s2 = "" # initialise a new empty string
- for x in range(0, len(s1)-1, 2): # start a loop counting in twos through the input string
- # but make sure we won't try to access a character beyond the end
- s2 += s1[x+1] # add the 2nd character of a pair to our new string
- s2 += s1[x] # add the first character of a pair to our new string
- # loop back to process the next pair
- if len(s1) & 1: # If the input string had an odd number of characters ...
- s2 += s1[-1] # ... then append the last remaining character to our new string
- return s2 # exit from the function, returning the new completed string
- tests = ["hello world", "behave now"] # define a list of strings to be processed by our function
- for test_string in tests: # extract one string at a time
- result = swap_pairs(test_string) # pass a string to our function and get the returned string
- print(test_string, " >> ", result) # print the original string and the processed string
- # Output:
- # hello world >> ehll oowlrd
- # behave now >> ebahevn wo
Add Comment
Please, Sign In to add comment