Python: Replace a string "Python" with "Java" and "Java" with "Python" in a given string
Swap Python and Java
Write a Python program to replace a string "Python" with "Java" and "Java" with "Python" in a given string.
Input:
English letters (including single byte alphanumeric characters, blanks, symbols) are given on one line. The length of the input character string is 1000 or less.
Input a text with two words 'Python' and 'Java'
Output:
Exchanged character string of Python and Java on one line.
Visual Presentation:
Sample Solution:
Python Code:
# Print statement to prompt the user to input a text with two words 'Python' and 'Java'
print("Input a text with two words 'Python' and 'Java'")
# Split the input text into a list of words
text = input().split()
# Iterate through each word in the text
for i in range(len(text)):
# Check if 'Python' is present in the current word
if "Python" in text[i]:
# Find the index of 'Python' in the current word
n = text[i].index("Python")
# Replace 'Python' with 'Java' in the current word
text[i] = text[i][:n] + "Java" + text[i][n + 6:]
# Check if 'Java' is present in the current word
elif "Java" in text[i]:
# Find the index of 'Java' in the current word
n = text[i].index("Java")
# Replace 'Java' with 'Python' in the current word
text[i] = text[i][:n] + "Python" + text[i][n + 4:]
# Print the modified text with replaced words
print(*text)
Sample Output:
Input a text with two words 'Python' and 'Java' Python is popular than Java Java is popular than Python
Explanation:
Here is a breakdown of the above Python code:
- First the code prompts the user to input a text with the two words 'Python' and 'Java'.
- User input is split into a list of words.
- It iterates through each word in the text.
- Checks if 'Python' is present in the current word and replaces it with 'Java'.
- Checks if 'Java' is present in the current word and replaces it with 'Python'.
- Prints the modified text with replaced words.
Flowchart:
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program which reads the two adjoined sides and the diagonal of a parallelogram and check whether the parallelogram is a rectangle or a rhombus.
Next: Write a Python program to find the difference between the largest integer and the smallest integer which are created by 8 numbers from 0 to 9. The number that can be rearranged shall start with 0 as in 00135668.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics