How do I swap letters around input in python?

So you take input like hello

Then replace the first digit with the third and replace the second digit with the fourth.

Result "Llheo"

+1
source share
3 answers

Here is a different approach. You need to manually specify which positions you want to swap. So, here you can change the value of swap_seq , which is just a sequence of string indexes.

For example, s[0]+s[1]+s[2]+s[3]+s[4] - "Hello", and s[2]+s[3]+s[0]+s[1]+s[4] - "llHeo".

 s="Hello" swap_seq="23014" swapped=''.join([s[int(i)] for i in swap_seq]) if s[0].isupper(): swapped.capitalize() print swapped 

Output: Llheo


Edit: swapped now capitalized only if s has capital letters

+3
source

This is not trivial. This can be done using row indexing and slicing. But you will also have to take into account the capitalization in place and keep it.

 >>> s = "Hello" >>> x = list(s) >>> x ['H', 'e', 'l', 'l', 'o'] 

Change w / third and swap case first

 >>> x[0], x[2] = x[2].upper(), x[0].lower() >>> x ['L', 'e', 'l', 'h', 'o'] 

Change second to fourth

 >>> x[1], x[3] = x[3], x[1] >>> x ['L', 'l', 'h', 'e', 'o'] 

Return it to the string

 >>> ''.join(x) 'Llheo' 

This will not work for all cases, but in this particular case this is what you requested.

Edit: Let's take it one step further with the function:

 def swap_letters(indexes, string): """ @indexes should be a list of 2-tuples of indexes to swap, eg: [(0,2), (1,3)] @string is the input string. """ letters = list(string) for src, dst in indexes: letter_src = letters[src] letter_dst = letters[dst] # Swap case on destination letter if src is upper if letter_src.isupper(): letter_dst = letter_dst.upper() letter_src = letter_src.lower() letters[src], letters[dst] = letter_dst, letter_src return ''.join(letters) if __name__ == '__main__': # This is the example from the OP indexes = [(0,2), (1,3)] word = 'Hello' print swap_letters(indexes, word) # And a proof of concept indexes = [(0,-1), (6,4)] word = 'ActiveSync' print swap_letters(indexes, word) 
+4
source

We can swap two letters with the word indexing and slicing. For example, to change the first and last letter of the word "Code", check the following code.

 string = "Code" s = list(string) s[0], s[len(s)-1] = s[len(s)-1].upper(), s[0].lower() string = ''.join(s) print(string) 

O / p: - "Eodc"

And this code can be applied universally to any word, regardless of the length of the word. Also by changing the index no. You can change the letters you want to change as follows:

 s[0], s[len(s)-2] = s[len(s)-2].upper(), s[0].lower() 

O / P: - "Doce"

0
source

Source: https://habr.com/ru/post/903529/


All Articles