python基于分隔符查找子字符串
我是Python新手,因此可能缺少一些简单的东西 我举了一个例子:python基于分隔符查找子字符串,python,regex,string,Python,Regex,String,我是Python新手,因此可能缺少一些简单的东西 我举了一个例子: string = "The , world , is , a , happy , place " 我必须创建由,分隔的子字符串,并分别打印它们和处理实例。 这意味着在这个例子中,我应该能够打印 The world is a happy place 我可以采取什么办法?我试图使用字符串查找功能,但是 Str[0: Str.find(",") ] 无法帮助查找第二个和第三个实例。字符串有一个split()方法用于此
string = "The , world , is , a , happy , place "
我必须创建由,
分隔的子字符串,并分别打印它们和处理实例。
这意味着在这个例子中,我应该能够打印
The
world
is
a
happy
place
我可以采取什么办法?我试图使用字符串查找功能,但是
Str[0: Str.find(",") ]
无法帮助查找第二个和第三个实例。字符串有一个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
循环打印单词。尝试使用拆分功能
在您的示例中:
string = "The , world , is , a , happy , place "
array = string.split(",")
for word in array:
print word
您的方法失败,因为您对它进行了索引,以从开始到第一个“,”都生成字符串。如果您然后从第一个“,”到下一个“,”对其进行索引,并以这种方式在字符串中进行迭代,那么这可能会起作用。不过拆分的效果会更好。另一种选择:
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
见
您也可以只使用match=re.findall(r'\w+',string)
就可以得到相同的输出。由于Python中方便的string方法,这很简单:
print "\n".join(token.strip() for token in string.split(","))
输出:
The
world
is
a
happy
place
顺便说一下,string
这个词对于变量名来说是一个糟糕的选择(Python中有一个string
模块)