【问题标题】:Getting a sub-string from a string? [duplicate]从字符串中获取子字符串? [复制]
【发布时间】:2016-10-27 00:58:01
【问题描述】:

有没有办法在 python 中提取字符串中的每个子字符串?

例如,如果我有字符串

"Hello there my name is Python" 

我想从该字符串中取出每个子字符串(或单个单词),以便从该字符串中取出"Hello", "there" , "my" , "name" , "is""Python"

【问题讨论】:

标签: python string python-2.7


【解决方案1】:

我相信您正在寻找的是split 方法。

它将用指定的分隔符打破字符串。默认分隔符是空格。

input_string = "Hello there my name is Python" 
for substring in input_string.split():
    print(substring)

【讨论】:

    【解决方案2】:

    使用split() 字符串方法。

    >>> sentence = 'Hello there my name is Python'
    >>> words = sentence.split()
    >>> print words
    ['Hello', 'there', 'my', 'name', 'is', 'Python']
    

    【讨论】:

      猜你喜欢
      • 2014-06-14
      • 2013-08-12
      • 1970-01-01
      • 1970-01-01
      • 2014-07-11
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      相关资源
      最近更新 更多