【问题标题】:remove specific characters from text file string从文本文件字符串中删除特定字符
【发布时间】:2013-08-08 10:45:41
【问题描述】:

我有一个文本文件,其中包含以下行:('larry', 3, 100) 我需要使用 a 将它的三个部分分配给不同的变量 方法接近我下面的方法。到目前为止,我可以分解它, 但我无法从结果中删除括号和撇号。 我已经在 stackover 上尝试了几个小时的其他解决方案,但无济于事......

filecontent = filename.read().strip().split(',')

for i in filecontent:
    name = filecontent[0]
    weeks_worked = filecontent[1]
    weekly_payment = filecontent[2] 

print ("name:" + name)
print ("weeks worked:" + weeks_worked)
print ("weekly payment:" + weekly_payment)

给出结果:

姓名:('拉里'

工作周数:3

每周付款:100)

如何让它只显示:

姓名:拉里

工作周数:3

每周付款:100

【问题讨论】:

    标签: python file variables python-3.x


    【解决方案1】:

    您需要在此处使用ast.literal_eval,它将字符串转换为元组:

    import ast
    filecontent = ast.literal_eval(filename.read().strip())
    

    你也不需要for循环,你也可以这样做:

    name, weeks_worked, weekly_payment = filecontent
    

    【讨论】:

      【解决方案2】:

      您可以在拆分之后或之前使用正则表达式。

          filecontent = filename.read().strip().split(',')
      
          for i in filecontent:
              name = re.sub(r'\(|\)|\'','',filecontent[0])
              weeks_worked =  re.sub(r'\(|\)|\'','',filecontent[1])
              weekly_payment = re.sub(r'\(|\)|\'','',filecontent[1])
      

      或者我更愿意这样做

         filecontent = re.sub(r'\(|\)|\'','',filename.read().strip()).split(',')
      

      然后做你平常的事情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多