acclivity

pySwapPairs

Feb 9th, 2021 (edited)
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. # Function to accept a string and swap pairs of characters
  2. # Mike Kerry - Feb 2021 - acclivity2@gmail.com
  3.  
  4. # Examples
  5. # "hello world" becomes "ehll oowlrd"
  6. # "behave now" becomes "ebahevn wo"
  7.  
  8.  
  9. def swap_pairs(s1):                     # Define a function to do the work. "s1" contains the string to be processed
  10.  
  11.     # We cannot directly change the input string, because strings in Python are "immutable" (cannot be modified)
  12.  
  13.     s2 = ""                             # initialise a new empty string
  14.     for x in range(0, len(s1)-1, 2):    # start a loop counting in twos through the input string
  15.                                         # but make sure we won't try to access a character beyond the end
  16.  
  17.         s2 += s1[x+1]                   # add the 2nd character of a pair to our new string
  18.         s2 += s1[x]                     # add the first character of a pair to our new string
  19.                                         # loop back to process the next pair
  20.  
  21.     if len(s1) & 1:                     # If the input string had an odd number of characters ...
  22.         s2 += s1[-1]                    # ... then append the last remaining character to our new string
  23.  
  24.     return s2                           # exit from the function, returning the new completed string
  25.  
  26.  
  27. tests = ["hello world", "behave now"]   # define a list of strings to be processed by our function
  28.  
  29. for test_string in tests:               # extract one string at a time
  30.     result = swap_pairs(test_string)    # pass a string to our function and get the returned string
  31.     print(test_string, " >> ", result)  # print the original string and the processed string
  32.  
  33. # Output:
  34. # hello world  >>  ehll oowlrd
  35. # behave now  >>  ebahevn wo
  36.  
Add Comment
Please, Sign In to add comment