Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how can I replace letters from each word and combine them together without function

I have this string

my_string = 'abc ' 'xyz'

I need to replace the first two letters of the first word with the first two letters of the last word
is it possible to do it without the mix.up function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading