如何在Python中替换字符串中的子字符串?

2024-09-27 19:23:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想替换字符串中的子字符串价值观。但是,在没有任何字符串组的情况下替换单个字符串并不容易。你知道吗

我有这样的数据:

S.no      Name                     Expected Result
------    ----------------------   ----------------------
1         2341 blvd                2341 Boulevard
2         648 s Kingston rd        648 S Kingston Road
3         sw Beverly st            SW Beverly Street

Tags: 数据no字符串name情况rdresultsw
1条回答
网友
1楼 · 发布于 2024-09-27 19:23:24
def wordreplace(s, d):
    """Replaces words in string by dict d. # Thank you @Patrick Artner
    for improving dict call to d.get(w, w)!"""
    return ' '.join([ d.get(w, w) for w in s.split()])


# this was my old version:
# def wordreplace(s, d):
#    """Replaces words in string by dict d."""
#    return ' '.join([ d[w] if w in d else w for w in s.split()])

d = {'blvd': 'Boulevard', 'st': "Street", 'sw': 'SW', 's': "S", 'rd': '
Road'}

s1 = "2341 blvd"

s2 = "648 s Kingston rd"

s3 = "sw Beverly st"

wordreplace(s1, d)
# '2341 Boulevard'

wordreplace(s2, d)
# '648 S Kingston Road'

wordreplace(s3, d)
# 'SW Beverly Street'

默认情况下,s.split()按单个空格分隔,因此返回字符串s的单词列表。每个单词都加载到变量w中。列表表达式的for w in s.split()部分。 在for之前的部分确定在结果列表中收集的内容。你知道吗

if w in d意思是:测试单词是否在给定的替换词典中d。它查看d.keys()字典的键。找到时,它返回字典值d[w]else它返回单词本身w。你知道吗

结果列表是使用' '作为连接元素的join,因此单词列表被重新转换为字符串。你知道吗

列表表达式非常方便,常常导致这样的单行函数。所以强烈建议你去学习。你知道吗

除了在字典表单中键入所有键值之外,您还可以执行以下操作:

keys = [ # list here all keys ]
vals = [ # list here all corresponding values in the right order ]
d = {k: vals[i] for i, k in enumerate(keys)}

同样,您可以使用列表表达式的功能来生成字典。你知道吗

# abstract it to a function
def lists2dict(keys_list, vals_list):
    return {k, vals_list[i] for i, k in enumerate(key_list)}

# and then call:
d = lists2dict(keys, vals)

相关问题 更多 >

    热门问题