第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何替換字符串的多個子字符串?

如何替換字符串的多個子字符串?

翻翻過去那場雪 2019-06-09 14:11:45
如何替換字符串的多個子字符串?我想使用.替換函數(shù)替換多個字符串。我現(xiàn)在string.replace("condition1", "")但我想要的是string.replace("condition1", "").replace("condition2", "text")雖然這感覺不像是好的語法做這件事的正確方法是什么?有點像grep/regex中你能做什么\1和\2將字段替換為某些搜索字符串
查看完整描述

3 回答

?
慕雪6442864

TA貢獻1812條經(jīng)驗 獲得超5個贊

下面是一個應(yīng)該使用正則表達式的簡短示例:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here# use these three lines to do the replacementrep 
= dict((re.escape(k), v) for k, v in rep.iteritems()) #Python 3 renamed dict.iteritems to dict.items so use rep.items()
 for latest versionspattern = re.compile("|".join(rep.keys()))text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

例如:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")'() and --text--'


查看完整回答
反對 回復(fù) 2019-06-09
?
牛魔王的故事

TA貢獻1830條經(jīng)驗 獲得超3個贊

你可以做一個很好的循環(huán)功能。

def replace_all(text, dic):
    for i, j in dic.iteritems():
        text = text.replace(i, j)
    return text

哪里text是完整的字符串和dic是一個字典-每個定義都是一個字符串,將取代一個匹配的術(shù)語。

在Python 3中,iteritems()已被替換為items()


小心:Python字典沒有可靠的迭代順序。只有在以下情況下,此解決方案才能解決問題:

  • 替換順序無關(guān)
  • 更換之前的替換結(jié)果是可以的

例如:

d = { "cat": "dog", "dog": "pig"}mySentence = "This is my cat and this is my dog."replace_all(mySentence, d)print(mySentence)

可能的產(chǎn)出#1:

"This is my pig and this is my pig."

可能的輸出#2

"This is my dog and this is my pig."

一個可能的解決方法是使用OrderedDict。

from collections import OrderedDictdef replace_all(text, dic):
    for i, j in dic.items():
        text = text.replace(i, j)
    return text
od = OrderedDict([("cat", "dog"), ("dog", "pig")])mySentence = "This is my cat and this is my dog."replace_all(mySentence, od)
print(mySentence)

產(chǎn)出:

"This is my pig and this is my pig."

小心#2:如果你text字符串太大了,或者字典里有很多對。


查看完整回答
反對 回復(fù) 2019-06-09
?
開心每一天1111

TA貢獻1836條經(jīng)驗 獲得超13個贊

下面是第一種解決方案的變體,如果您喜歡功能的話,可以使用Reduce。*)

repls = {'hello' : 'goodbye', 'world' : 'earth'}s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls.iteritems(), s)

馬丁諾的更好版本:

repls = ('hello', 'goodbye'), ('world', 'earth')s = 'hello, world'reduce(lambda a, kv: a.replace(*kv), repls, s)


查看完整回答
反對 回復(fù) 2019-06-09
  • 3 回答
  • 0 關(guān)注
  • 662 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號