Skip to main content
 首页 » 编程设计

python之根据python中列中的子字符串对文本文件进行排序

2024年10月24日22txw1958

我有一组格式的文本文件数据:

19500101     9.2 
19510101     100 
19520101     28 
19500102     33 
19510102     34 
19520102     102   

我试图只查看第一列中最后 4 个字符是子字符串“0101”的那些值。

我已经使用了这个 Python for 循环并获得了这些值,但我也获得了字符串其他部分中有“0101”的实例。例如:20101231

for line in iter(f): 
if line.split(None, 1)[0].find('0101') != -1: 
    print(line) 

我该如何修改这个循环以获得我想要的输出?

请您参考如下方法:

考虑使用 endswith 根据 string 的结尾检查此类匹配,以使其更直观和更易读:

for line in iter(f): 
    if line.split(None, 1)[0].endswith('0101'): //clear and intuitive 
        print(line) 

如果您也确切知道字符的位置,还有其他选择,只是不太直观:

for line in iter(f): 
    if line.split(None, 1)[0][4:] == '0101': //start from index 4 from front till the end 
        print(line) 

或者

for line in iter(f): 
    if line.split(None, 1)[0][-4:] == '0101': //start from index 4 from back till the end 
        print(line) 

虽然都是有效的