在python中用通配符分隔字符串

Mic*_*l R 1 python string partition

我有一个看起来像的文件

 12 MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
  8 O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01
Run Code Online (Sandbox Code Playgroud)

我想从行的前面分出数字,输出为

MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01
Run Code Online (Sandbox Code Playgroud)

我有这个

for line in file:
    head, sep, tail = line.partition('wildcard')
    print tail
Run Code Online (Sandbox Code Playgroud)

我应该为通配符添加什么?

Mar*_*ers 6

您的格式看起来像固定列格式,其中每列具有固定宽度.

如果是这样,请改为使用切片:

for line in file:
    print line[4:]
Run Code Online (Sandbox Code Playgroud)

切掉前4个字符.

或者,在空格上拆分一次,None参数为str.split():

for line in file:
    tail = line.split(None, 1)[-1]
    print tail
Run Code Online (Sandbox Code Playgroud)

str.split(None) 在字符串的开头跳过空格,并在第一列之后的第一个空白字符序列上拆分.[-1]采取最后一个元素; 即使行上只有一列,你也会得到一个结果.

演示:

>>> line = ' 16 S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01\n'
>>> line.split(None, 1)
['16', 'S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01\n']
Run Code Online (Sandbox Code Playgroud)


the*_*eye 5

您可以使用,

head, sep, tail = line.strip().partition(" ")
Run Code Online (Sandbox Code Playgroud)

整个程序就像这样

with open("Input.txt") as inFile:
    for line in inFile:
        print line.strip().partition(" ")[2]
Run Code Online (Sandbox Code Playgroud)

产量

MG   -5.000000000000E-01 -5.000000000000E-01  0.000000000000E+00
S     1.558454815345E-01  1.558454815345E-01  2.500000000000E-01
O     2.189546044408E-01 -1.271822846411E-01  4.012978695812E-01
Run Code Online (Sandbox Code Playgroud)