【问题标题】:Spliting a python list with two delimeters [duplicate]用两个分隔符拆分python列表[重复]
【发布时间】:2019-03-04 16:53:59
【问题描述】:

我开始学习python。我想知道如何拆分有两个分隔符的列表。

输入

1,2,3,4,5;2

我的代码:

with open(path, 'r') as f:
for fs in f:
    ip= fs.rstrip('\n').split(',')
    print (ip)

我的输出:

['1', '2', '3', '4', '5;2']

期望的输出

['1', '2', '3', '4', '5', '2']

请问现在如何删除列表中的分号。

谢谢

【问题讨论】:

    标签: python python-3.x python-2.7 python-requests


    【解决方案1】:

    您可以将所有分隔符转换为一个分隔符,例如 replacetranslate

    str.replace(old, new[, max])

    你可以这样做:

    print str.replace(";", ",")

    然后拆分

    https://www.tutorialspoint.com/python/string_replace.htm

    【讨论】:

      【解决方案2】:

      使用正则表达式将;替换为,

      import re
      new_input=re.sub(';',',','1,2,3,4,5;2')
      print(new_input.split(','))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-04-25
        • 2018-06-18
        • 1970-01-01
        • 1970-01-01
        • 2018-11-28
        • 2011-06-09
        • 1970-01-01
        • 2021-11-08
        相关资源
        最近更新 更多