There is a line, for example: "abc23z18pK1", you need to get "abc18z13pK2", that is, the sequence of numbers is changed, so that the letters do not change. I already through replace, and with the help of the re module I tried, it does not work for me! And you need not just swap places, namely, “reflect” the numbers, this is the condition that they set for me. Can you tell how this can be done with writing a not very large code?
3 answers
s = 'abc23z18pK1' it = iter([i for i in s if i.isdigit()][::-1]) mirrored = ''.join(next(it) if c.isdigit() else c for c in s) print(mirrored) # abc18z13pK2 |
So far, I came up with
word = "abc23z18pK1" numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] rotated = [] result = "" for i in word: if i in numbers: rotated.append(i) rotated.reverse() it = 0 for i in word: if i in numbers: result += rotated[it] it += 1 else: result += i print(result) abc18z13pK2
- Please add the result to the answer - gil9red
- Yes of course .... - ishidex2
- Kst, here's an example of how to fill in one line:
rotated = [i for i in word if i in '0123456789']And the conditionif i in '0123456789'is the same asif i.isdigit()- gil9red
|
I threw in a simple algorithm for cunningly replacing values by key:
text = "abc23z18pK1" import re items = re.findall('([a-zA-Z]+)(\d+)', text) print(items) # [('abc', '23'), ('z', '18'), ('pK', '1')] # Словарь параметров value_by_key = dict(items) print(value_by_key) # {'abc': '23', 'z': '18', 'pK': '1'} # Зададим словарь подмены replacement = { 'abc': '777', 'pK': '9', } # Выполним подмену new_text = text for k, v in replacement.items(): old_value = k + value_by_key[k] new_value = k + v new_text = new_text.replace(old_value, new_value) print(new_text) # abc777z18pK9 - Damn, I thought the question was just a substitution, and only then I saw that as a result, the same figures, but in the reverse order :) - gil9red
|
"abc23z18pK1".replace("abc23", "abc18").replace("z18", "z13").replace("pK1", "pK2")? - gil9red