Replace multiple lines at once

Suppose I have this line "abcd"

Now I want to replace all 'a with' d ', and I want to replace all' d with 'a'. The problem is that string.replace does not work in this situation.

"abcd" .replace ('a', 'd'). replace ('d', 'a')

ABCA

Expected Result: "dbca"

How would I understand that?

+5
source share
3 answers

You can use .translate() .

Returns a copy of the string in which each character was displayed through the specified translation table.

https://docs.python.org/3/library/stdtypes.html#str.translate

Example:

 >>> "abcd".translate(str.maketrans("ad","da")) 'dbca' 
+5
source

You can use list comprehension to switch the values ​​you want

 x = "abcd" ''.join(['d' if i == 'a' else 'a' if i == 'd' else i for i in x]) 

'DBCA'


No list

 x = "abcd" ''.join('d' if i == 'a' else 'a' if i == 'd' else i for i in x) 

'DBCA'


Timing

 In [1]: x = "abcd"*10000000 In [2]: %timeit ''.join('d' if i == 'a' else 'a' if i == 'd' else i for i in x) 5.78 s ± 152 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) In [3]: %timeit ''.join(['d' if i == 'a' else 'a' if i == 'd' else i for i in x]) 4.49 s ± 157 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) 

It turns out that list comprehension is a little faster.

+1
source

you can try python to replace the recipe:

 string_word="abcd" data=list(string_word) replace_index=list({j:i for j,i in enumerate(data) if i=='a' or i=='d'}.keys()) data[replace_index[0]],data[replace_index[1]]=data[replace_index[1]],data[replace_index[0]] print("".join(data)) 

output:

 dbca 
0
source

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


All Articles