python - 在 python 中拆分项目并附加一些项目

标签 python split

我想使用 : 拆分器拆分第一个项目,但拒绝第二个项目等。

我有一个包含以下内容的文件:

# cat myfile
one:two
three:four
five:six:seven
eight:nine:ten

我用 python 尝试过的是:

with open('myfile','r') as f:
    for line in f:
        for word in line.split():
            item1=word.split(':')[0]
            item2=word.split(':')[1:]
            print 'Item1: '+item1+' Item2: '+str(item2)

结果是:

Item1: one Item2: ['two']
Item1: three Item2: ['four']
Item1: five Item2: ['six', 'seven']
Item1: eight Item2: ['nine', 'ten', 'eleven']

但我想要以下结果:

Item1: one Item2: two
Item1: three Item2: four
Item1: five Item2: sixseven
Item1: eight Item2: nineteneleven

最佳答案

您可以拆分一次,然后使用 str.replacestr.translate 来删除 :,您还应该拆分一次并解压:

In [6]: word,rest = s.split(":",1)

In [7]: rest = rest.translate(None,":")

In [8]: word,rest
Out[8]: ('eight', 'nineten')

使用替换:

In [9]: s = "eight:nine:ten"
In [10]: word,rest = s.split(":",1)    
In [11]: rest = rest.replace(":","")    
In [12]: rest
Out[12]: 'nineten'

对于 python 3,你需要传递一个字典来翻译:

word, rest = s.split(":",1)
rest = rest.translate({ord(":"): ""})

print(word,rest)

您也不需要迭代分割线:

with open("test.txt") as f:
    for line in f:
        word, rest = line.rstrip().split(":", 1)
        print('Item1: {} Item2: {}'.format(word,rest.translate(None,":"))

输出:

Item1: one Item2: two
Item1: three Item2: four
Item1: five Item2: sixseven
Item1: eight Item2: nineten

关于python - 在 python 中拆分项目并附加一些项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30073215/

相关文章:

arrays - Ruby String Split on "\t"丢失 "\n"

python - 一行Python中的多个整数输入

arrays - 如何将文件拆分为数组并找到每个数组中的最大值

python - 将列表项转换为 int 并将它们相加的最有效方法

python - 在 Python 中计算图像数据集 channel 明智均值和标准差的最快方法

python - Scrapy:Python找不到蜘蛛

java - 你需要在 Java 中转义 * 字符吗?

python - cifar10 随机化训练和测试集

python - 如何在 Apache Beam/Google 数据流中将大窗口缩小为较小的窗口?

vb.net - 拆分字符串并为变量赋值