gpt4 book ai didi

python - 如何替换参数给定的字符串中的特定元素

转载 作者:太空宇宙 更新时间:2023-11-04 11:07:04 25 4
gpt4 key购买 nike

我想做的是遍历一个字符串,选择一个名称和一个当前在字符串中的职位,然后它会找到职位所在的行,然后将当前名称替换为在参数中选择的新名称。

这是我的字符串:

TV = '''
Tulleveien Velforening
leder: Kari
kasserer: Ole
IT-ansvarlig: Liv
parkeringsansvarlig: Kari
arrangementsansvarlig: Liv
hagekonsulent: Kari
brannansvarlig: Kari
'''

然后这是我试图运行以实际执行它的函数:

def Verv(navn, vervs):
print("Tulleveien Velforening")
for lines in TV.split("\n"):
lines.replace(navn, lines)
return TV

这是我尝试过的:

Verv('Roald', ["leder", "IT-ansvarlig"])

但是当我运行该程序时,我得到的只是它开始时的列表。预期的输出是:

Tulleveien Velforening
leder: Roald
kasserer: Ole
IT-ansvarlig: Roald
parkeringsansvarlig: Kari
arrangementsansvarlig: Liv
hagekonsulent: Kari
brannansvarlig: Kari

我该如何解决这个问题?

最佳答案

试试这个,我添加了一些应该解释逻辑的内联注释。

TV = '''
Tulleveien Velforening
leder: Kari
kasserer: Ole
IT-ansvarlig: Liv
parkeringsansvarlig: Kari
arrangementsansvarlig: Liv
hagekonsulent: Kari
brannansvarlig: Kari
'''


def Verv(navn, verv):
# Created an empty dictionary to convert the lines into a dictionary which is much easier to manage.
rin_dict = {}
print("Tulleveien Velforening")
# Forming a dictionary out of your string.
for line in TV.split("\n"):
if ":" in line:
rin = line.split(": ")
rin_dict[rin[0]] = rin[1]
# Dictionary key replacement.
for elm in verv:
rin_dict[elm] = navn
# Printing back the dictionary in your desired format.
for k, v in rin_dict.items():
print("{0}: {1}".format(k, v))


# The second argument is a list.
Verv('Roald', ["leder", "IT-ansvarlig"])

关于python - 如何替换参数给定的字符串中的特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59180077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com