Write a Python Program to Swap elements in String list


The program is a python script that replaces specific words in a list of strings with new words.

Here's what the program does in detail:

  • A list of strings "s" is defined with 4 strings.
  • The original list "s" is printed using the "print()" function, with the message "Before Swap".
  • A list comprehension is used to create a new list "res" by replacing specific words in the original list "s".
  • The "replace()" method is used to replace the words in each string of the list "s". For example, the word "joes" is replaced with "Joe's", the word "Computer" is replaced with "Software", and the word "Education" is replaced with "Solutions".
  • The final list "res" is printed after the replacement of the words, with the message "After Swap".

Source Code

s = ["Tutor","joes","Computer","Education"]
 
print("Before Swap :",s)
 
res = [sub.replace("joes","Joe's").replace("Computer", "Software").replace("Education", "Solutions") for sub in s]
 
print ("After Swap : ",res)

Output

Before Swap : ['Tutor', 'joes', 'Computer', 'Education']
After Swap :  ['Tutor', "Joe's", 'Software', 'Solutions']

Example Programs