鱼C论坛

 找回密码
 立即注册
查看: 1032|回复: 2

[已解决]怎样去掉字符串中字符

[复制链接]
发表于 2018-3-18 16:47:58 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
输入文档结果是:
43  ['23', '2', '22', '1']
32  ['45', '1', '12', '1']
12  ['32', '1', '2', '1']
11  ['1', '2', '43', '1']
23  ['43', '1']
44  ['3', '1']
22  ['1', '3', '3', '1', '43', '1']
33  ['2', '1']

怎样把他们符号去掉,改成这样:
43  23  2  22  1
32  45  1  12  1
12  32  1  2    1
11  1    2  43  1
23  43  1
44  3    1
22  13  3  1   43  1
33  2    1

如何用python编程?求助大佬!
最佳答案
2018-3-18 17:22:46
本帖最后由 ba21 于 2018-3-18 17:27 编辑

更改楼上代码:
  1. with open(r"1.txt", "r") as f:
  2.     txt = f.read()
  3.     txt = txt.replace('[','').replace(']','').replace(',',' ').replace('\'','')
  4.         
  5. with open(r"2.txt", "w") as f:
  6.     f.write(txt)
复制代码


  1. def joinstr(line):
  2.     line = line[:-1] #去掉尾部\n
  3.     line = line.split("  ") #以2个空格做为分割
  4.     str1 = line[0]
  5.     str2 = line[1]

  6.     temp = ''   
  7.     for i in str2[1:-1].split(','): # 去掉['2', '1']的[]后'2', '1'取,号分割后的元组
  8.         temp += i.strip()[1:-1] + ' ' # 去掉空格后取 '2' 中间的数字 2
  9.     return str1+' '+temp

  10. txt = []
  11. with open(r"1.txt", "r") as f:
  12.     for line in f:
  13.         txt.append(joinstr(line))
  14.         
  15. with open(r"2.txt", "w") as f:
  16.     for line in txt:
  17.         f.writelines(line+'\n') #尾部加入\n 写入文件
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2018-3-18 17:20:40 | 显示全部楼层
  1. s.replace('[','').replace(']','').replace(',',' ').replace('\'','')
复制代码

s是你的字符串
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

发表于 2018-3-18 17:22:46 | 显示全部楼层    本楼为最佳答案   
本帖最后由 ba21 于 2018-3-18 17:27 编辑

更改楼上代码:
  1. with open(r"1.txt", "r") as f:
  2.     txt = f.read()
  3.     txt = txt.replace('[','').replace(']','').replace(',',' ').replace('\'','')
  4.         
  5. with open(r"2.txt", "w") as f:
  6.     f.write(txt)
复制代码


  1. def joinstr(line):
  2.     line = line[:-1] #去掉尾部\n
  3.     line = line.split("  ") #以2个空格做为分割
  4.     str1 = line[0]
  5.     str2 = line[1]

  6.     temp = ''   
  7.     for i in str2[1:-1].split(','): # 去掉['2', '1']的[]后'2', '1'取,号分割后的元组
  8.         temp += i.strip()[1:-1] + ' ' # 去掉空格后取 '2' 中间的数字 2
  9.     return str1+' '+temp

  10. txt = []
  11. with open(r"1.txt", "r") as f:
  12.     for line in f:
  13.         txt.append(joinstr(line))
  14.         
  15. with open(r"2.txt", "w") as f:
  16.     for line in txt:
  17.         f.writelines(line+'\n') #尾部加入\n 写入文件
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-25 03:51

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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