[Solved] how can I replace letters from each word and combine them together without function [closed]


You can you string slices like so:

my_string = 'abc ' 'xyz'
my_string = my_string.split()
output = my_string[1][:2] + my_string[0][2:] + " " + my_string[0][:2] + my_string[1][2:]
print(output)

Output:

xyc abz

If you want the string to have ' in between the letters you can do:

output = my_string[1][:2] + my_string[0][2:] + "' '" + my_string[0][:2] + my_string[1][2:]

Output:

xyc' 'abz

OR

output = "'" + my_string[1][:2] + my_string[0][2:] + "' '" + my_string[0][:2] + my_string[1][2:] + "'"

Output:

'xyc' 'abz'

But I believe the first output is most useful.

You can do it without a function like so:

my_string = 'abc ' 'xyz'
output = my_string[4:6] + my_string[2:4] + my_string[:2] + my_string[-1:]
print(output)

Output:

xyc abz

If you have the strings separate before they are combinined you could do:

s1 = 'abc'
s2 = 'xyz'
output = s2[:2] + s1[2:] + " " + s1[:2] + s2[2:]
print(output)

Output:

xyc abz

7

solved how can I replace letters from each word and combine them together without function [closed]