我遇到了一个循环,在这里我尝试寻找几个月来将其翻译成法语。确实有效,但是当我在同一字符串中有两个月时,只会翻译第一个月。
for x in results:
if "January" in datestring:
x["auction_date"] = datestring.replace("January", "janvier")
elif "February" in datestring:
x["auction_date"] = datestring.replace("February", "février")
...
如果字符串为"31 may - 1 June 2019"
,则结果为"31 mai - 1 June 2019"
。
答案 0 :(得分:3)
请不要执行elif
部分!
for x in results:
if "January" in datestring:
datestring = datestring.replace("January", "janvier")
if "February" in datestring:
datestring = datestring.replace("February", "février")
# ...
x["auction_date"] = datestring
如果有动力,甚至可以单行完成:
datestring.replace("January", "janvier").replace("February", "fevrier") #...
作为替换,如果没有匹配的字符串,请勿替换
以更具可读性的方式:
months = [("janvier", "january"), ("fevrier", "february"), ("mars", "march")]
for french_m, english_m in months:
datestring.replace(english_m, french_m)