Python: Get a single string from two given strings, separated by a space and swap the first two characters of each string
Python String: Exercise-5 with Solution
Write a Python program to get a single string from two given strings, separated by a space and swap the first two characters of each string.
Sample Solution:
Python Code:
# Define a function named chars_mix_up that takes two arguments, 'a' and 'b'.
def chars_mix_up(a, b):
# Create a new string 'new_a' by taking the first two characters from 'b' and combining
# them with the characters from 'a' starting from the third character.
new_a = b[:2] + a[2:]
# Create a new string 'new_b' by taking the first two characters from 'a' and combining
# them with the characters from 'b' starting from the third character.
new_b = a[:2] + b[2:]
# Concatenate 'new_a', a space character, and 'new_b' to create a single string.
return new_a + ' ' + new_b
# Call the chars_mix_up function with the arguments 'abc' and 'xyz' and print the result.
print(chars_mix_up('abc', 'xyz')) # Output: 'xyc abz'
Sample Output:
xyc abz
Flowchart:
Python Code Editor:
Previous: Write a Python program to get a string from a given string where all occurrences of its first char have been changed to '$', except the first char itself.
Next: Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/string/python-data-type-string-exercise-5.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics