Write a program to swap the first n characters of two strings.

by

Last updated on Nov 5, 2022
Python Practicals (Question 6)

Input

test1 = input("enter the first string \n")
test2 = input("enter the second string \n")
to_swap = int(input("enter the number of characters to swap \n"))
if len(test1) < to_swap or len(test2) < to_swap:
    print("please enter a valid value :(")
else:
    x = test1[0:to_swap]
    test1 = test1.replace(test1[0: to_swap], test2[0: to_swap])
    test2 = test2.replace(test2[0: to_swap], x)
    print('first swapped string is ' + test1)
    print('second swapped string is ' + test2)

Output

enter the first string 
hello 
enter the second string 
there
enter the number of characters to swap 
4
first swapped string is thero 
second swapped string is helle

How useful was this post?

5 star mean very useful & 1 star means not useful at all.

Average rating 5 / 5. Vote count: 1

No votes so far! Be the first to rate this post.

Tags: