在字符串中查找双倍空格-Python [英] Finding double-spaces in a string - Python

查看:71
本文介绍了在字符串中查找双倍空格-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能找到更Python的,更漂亮的解决方案吗?

Can anyone find a more Python'ic, more beautiful solution?

我正在浏览文件中的某些文本行,以检查它们是否符合特定条件.由于某种原因,决定该行内部的分隔符为‘,即双倍空格.

I’m looping through some text lines in a file, to check if they meet certain criteria. For some reason it was decided that separators internally in the line is ‘ ‘, i.e. double space.

如何检查文本字符串以验证所有分隔符是否恰好是两个空格?该行末尾的空格不是问题,因为该行最初是.strip()的.

How do I check a text string to verify that all separators are exactly two spaces? Spaces at the end of the line is not an issue, as the line is initially .strip()’ed.

我已经写了这个,而且可以用,但是很难看.该代码将显示给某些Python新手,所以我正在寻找一个更短,更清晰,更漂亮的解决方案……

I have written this, and it works – but it’s ugly. The code will be shown to some Python newbie’s, so I’m looking for a shorter, clearer and more beautiful solution…

ll = ["53.80  64-66-04.630N  52-16-15.355W 25-JUN-1993:16:48:34.00  S10293..  2",
      " 53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2",
      "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2",
      "  53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2",
      "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2 ",
      "53.80  64-66-04.630N  52-16-15.355W  25-JUN-1993:16:48:34.00  S10293..  2  ",
      "53.80  64-66-04.630N  52-16-15.355W   25-JUN-1993:16:48:34.00  S10293..  2"]

for ln in ll:
    l = ln.strip()
    bolDS = True
    for n in range(len(l)-1):
        if (n>0 and l[n]==' ' and not ((l[n]==l[n+1])^(l[n]==l[n-1]))):
            bolDS = False

    print "|"+l+"|",bolDS

推荐答案

def is_doublespace_separated(input_string):
    return '  '.join(input_string.split()) == input_string.strip()

这行得通,因为 string.split 会将您的字符串分割为任何空格.和 string.join 将列表与分隔符 string 连接起来.在这种情况下,我们使用分隔符''(两个空格)重新连接您的字符串,然后将其与剥离的版本进行比较(我知道您已经知道剥离的作用).

This works because string.split will split your string on any whitespace. and string.join joins the list with the separator string. In this case, we use the separator ' ' (two spaces) to re-join your string and then compare it against the stripped version (I sense you already know what strip does).

**这将忽略字符串开头和结尾的空格.

**This will ignore whitespace at the front of the string as well as at the end.

这篇关于在字符串中查找双倍空格-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆