Список замен строк в Python

Следующий сценарий даст сообщение в Chrome и IE:

<script>
window.onbeforeunload = function (e) {
// Your logic to prepare for 'Stay on this Page' goes here 

    return "Please click 'Stay on this Page' and we will give you candy";
};
</script>

Chrome enter image description here [/g0]

IE enter image description here [/g1]

в Firefox вы получите общее сообщение

enter image description here [/g2]

Механизм синхронный, поэтому серверные вызовы на задержку не будут работать, вы все равно можете подготовить механизм, подобный модальное окно, которое отображается, если пользователь решит остаться на странице, но не сможет помешать ему уйти.

Ответ на вопрос в комментарии

F5 снова запустит событие, так что Atl + F4.

29
задан Lightness Races in Orbit 2 April 2016 в 02:28
поделиться

5 ответов

Похоже, хорошая возможность использовать цикл:

mapping = { 'A':'1', 'B':'2', 'C':'3', 'D':'4', 'E':'5'}
for k, v in mapping.iteritems():
    my_string = my_string.replace(k, v)

Более быстрый подход, если вы не возражаете против скобок будет:

mapping = [ ('A', '1'), ('B', '2'), ('C', '3'), ('D', '4'), ('E', '5') ]
for k, v in mapping:
    my_string = my_string.replace(k, v)
58
ответ дан 27 November 2019 в 22:57
поделиться

Вы можете легко использовать string.maketrans () для создания строки сопоставления для передачи в str.translate ():

import string
trans = string.maketrans("ABCDE","12345")
my_string = my_string.translate(trans)
40
ответ дан 27 November 2019 в 22:57
поделиться

Также посмотрите в str.translate () . Он заменяет символы в соответствии с отображением, которое вы предоставляете для строк Unicode, или иначе должен быть указан, на что заменить каждый символ с chr (0) на chr (255).

14
ответ дан 27 November 2019 в 22:57
поделиться

If you want to get the wrong answer, slowly, then use string.replace in a loop. (Though it does work in this case of no overlap among the patterns and replacements.)

For the general case with possible overlaps or a long subject string, use re.sub:

import re

def multisub(subs, subject):
    "Simultaneously perform all substitutions on the subject string."
    pattern = '|'.join('(%s)' % re.escape(p) for p, s in subs)
    substs = [s for p, s in subs]
    replace = lambda m: substs[m.lastindex - 1]
    return re.sub(pattern, replace, subject)

>>> multisub([('hi', 'bye'), ('bye', 'hi')], 'hi and bye')
'bye and hi'

For the special case of 1-character patterns and 1- or 0-character replacements, use string.maketrans.

12
ответ дан 27 November 2019 в 22:57
поделиться
replaceDict = {'A':'1','B':'2','C':'3','D':'4','E':'5'}       
for key, replacement in replaceDict.items():  
  my_string = my_string.replace( key, replacement )
8
ответ дан 27 November 2019 в 22:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: