我是Python的新手,所以我可能错过了一些简单的东西。
我举了一个例子:
string = "The , world , is , a , happy , place "
我必须创建用,
分隔的子字符串,并分别打印它们和处理实例。这意味着在这个例子中,我应该能够打印
The
world
is
a
happy
place
我可以采取什么方法?我正在尝试使用字符串查找功能,但是
Str[0: Str.find(",") ]
无助于查找第 2 个、第 3 个实例。
尝试使用 split
函数。
在您的示例中:
string = "The , world , is , a , happy , place "
array = string.split(",")
for word in array:
print word
您的方法失败了,因为您将其索引以生成从开始到第一个","的字符串。如果随后将其从第一个","索引到下一个","并以这种方式遍历字符串,则可以正常工作。不过,斯普利特的效果会好得多。
对此有一个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
循环打印单词。
另一种选择:
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 中方便的字符串方法,这很简单:
print "n".join(token.strip() for token in string.split(","))
输出:
The
world
is
a
happy
place
顺便说一下,string
这个词对于变量名来说是一个糟糕的选择(Python 中有一个string
模块)。