吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1285|回复: 13
收起左侧

[求助] python想批量替换,怎么完善下面的代码

  [复制链接]
ymhld 发表于 2021-3-8 16:05
本帖最后由 ymhld 于 2021-3-8 16:15 编辑

想把列表里的年月日都换成"-"

[Python] 纯文本查看 复制代码
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)

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

Megix 发表于 2021-3-8 16:11
Python里面这不是叫列表吗
 楼主| ymhld 发表于 2021-3-8 16:15
 楼主| ymhld 发表于 2021-3-8 16:20
Megix 发表于 2021-3-8 16:28

能把你想要的最终结果也写在代码的注释里面吗,我不是很懂你要解决什么问题。
pzx521521 发表于 2021-3-8 16:33
for 里面的东西(rtime)不能够修改的, 你可以创建一个新的变量和列表
个人认为转为字符串简单一点, 还少了一个循环
[Asm] 纯文本查看 复制代码
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)
lostlq 发表于 2021-3-8 16:45
[Python] 纯文本查看 复制代码
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)
ligxi 发表于 2021-3-8 17:07
[Python] 纯文本查看 复制代码
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)
微凉 发表于 2021-3-8 17:41
6666666666666
 楼主| ymhld 发表于 2021-3-9 06:46
ligxi 发表于 2021-3-8 17:07
[mw_shl_code=python,true]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 ["年","月","日"]这种方式是实现不了的?
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-6-17 23:30

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表