python想批量替换,怎么完善下面的代码
本帖最后由 ymhld 于 2021-3-8 16:15 编辑想把列表里的年月日都换成"-"
rrtime = ["1981-11-17 00:00:00", "1980.4.28", "1993.09.16", "1977.4", "","1981年1月"]
for rtime in rrtime:
for r in ["年","月","日"]:
rtime=str(rtime).replace(r,"-")
print (rtime)
rrtime = ["1981-11-17 00:00:00", "1980.4.28", "1993.09.16", "1977.4", "","1981年1月"]
for rtime in rrtime:
rtime=str(rtime).replace(r for r in ["年","月","日"],"-")
print (rtime) Python里面这不是叫列表吗 Megix 发表于 2021-3-8 16:11
Python里面这不是叫列表吗
对,一时短路,写成别的了 Megix 发表于 2021-3-8 16:11
Python里面这不是叫列表吗
有什么办法? ymhld 发表于 2021-3-8 16:20
有什么办法?
能把你想要的最终结果也写在代码的注释里面吗,我不是很懂你要解决什么问题。 for 里面的东西(rtime)不能够修改的, 你可以创建一个新的变量和列表
个人认为转为字符串简单一点, 还少了一个循环
rrtime = ["1981-11-17 00:00:00", "1980.4.28", "1993.09.16", "1977.4", "", "1981年1月"]
str_time = ",".join(rrtime)
for r in ["年", "月", "日", "."]:
str_time = str(str_time).replace(r, "-")
rrtime = str_time.split(',')
print(rrtime) rrtime = ["1981-11-17 00:00:00", "1980.4.28", "1993.09.16", "1977.4", "", "1981年1月"]
for rtime in rrtime:
for r in ["年", "月", "日", "."]:
if rtime.endswith(r):
rtime = str(rtime).replace(r, "")
else:
rtime = str(rtime).replace(r, "-")
print(rtime) import re
rrtime = ["1981-11-17 00:00:00", "1980.4.28", "1993.09.16", "1977.4", "", "1981年1月"]
# 需要替换的内容
rec = re.compile(r'[年月日]')
# 不替换多余的-
d1 = list(map(lambda x: rec.sub('-', x), rrtime))
print(d1)
# 替换多余的-
d2 = list(map(lambda y: y[:-1] if y.endswith('-') else y, map(lambda x: rec.sub('-', x), rrtime)))
print(d2)
6666666666666 ligxi 发表于 2021-3-8 17:07
import re
rrtime = ["1981-11-17 00:00:00", "1980.4.28", "1993.09.16", "1 ...
用rtime=str(rtime).replace(r for r in ["年","月","日"],"-")
即for r in ["年","月","日"]这种方式是实现不了的?
页:
[1]
2