【问题标题】:python find substrings based on a delimiterpython根据分隔符查找子字符串
【发布时间】:2013-09-15 03:41:42
【问题描述】:

我是 Python 新手,所以我可能会遗漏一些简单的东西。

举个例子:

 string = "The , world , is , a , happy , place " 

我必须创建以, 分隔的子字符串并分别打印它们和处理实例。 这意味着在这个例子中我应该能够打印

The 
world 
is 
a
happy 
place

我可以采取什么方法?我试图使用字符串查找功能,但是

Str[0: Str.find(",") ]

对查找第二、第三个实例没有帮助。

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    简单,感谢 Python 中方便的字符串方法:

    print "\n".join(token.strip() for token in string.split(","))
    

    输出:

    The
    world
    is
    a
    happy
    place
    

    顺便说一句,string 这个词是变量名的错误选择(Python 中有一个string 模块)。

    【讨论】:

      【解决方案2】:

      尝试使用split 函数。

      在你的例子中:

      string = "The , world , is , a , happy , place "
      array = string.split(",")
      for word in array:
          print word
      

      您的方法失败了,因为您将其编入索引以产生从开始到第一个“,”的字符串。如果您然后将它从第一个“,”索引到下一个“,”并以这种方式遍历字符串,这可能会起作用。不过拆分效果会好得多。

      【讨论】:

        【解决方案3】:

        字符串对此有一个split() 方法。它返回一个列表:

        >>> string = "The , world , is , a , happy , place "
        >>> string.split(' , ')
        ['The', 'world', 'is', 'a', 'happy', 'place ']
        

        如您所见,最后一个字符串有一个尾随空格。拆分这种字符串的更好方法是:

        >>> [substring.strip() for substring in string.split(',')]
        ['The', 'world', 'is', 'a', 'happy', 'place']
        

        .strip() 去除字符串末端的空格。

        使用for 循环打印单词。

        【讨论】:

          【解决方案4】:

          另一种选择:

          import re
          
          string = "The , world , is , a , happy , place "
          match  = re.findall(r'[^\s,]+', string)
          for m in match:
              print m
          

          输出

          The
          world
          is
          a
          happy
          place
          

          查看demo

          您也可以只使用match = re.findall(r'\w+', string),您将获得相同的输出。

          【讨论】:

            猜你喜欢
            • 2019-02-06
            • 1970-01-01
            • 2019-09-19
            • 1970-01-01
            • 2015-06-06
            • 2023-03-07
            • 2011-08-04
            • 2013-10-19
            • 1970-01-01
            相关资源
            最近更新 更多