MAG*_*MAG 7 python regex string
我是Python新手,所以我可能会遗漏一些简单的东西.
我给了一个例子:
string = "The , world , is , a , happy , place "
Run Code Online (Sandbox Code Playgroud)
我必须创建分隔的子字符串,并分别打印它们和处理实例.这意味着在这个例子中我应该能够打印
The
world
is
a
happy
place
Run Code Online (Sandbox Code Playgroud)
我可以采取什么方法?我试图使用字符串查找功能,但是
Str[0: Str.find(",") ]
Run Code Online (Sandbox Code Playgroud)
没有帮助找到第二,第三个实例.
DHa*_*dle 14
尝试使用该split功能.
在你的例子中:
string = "The , world , is , a , happy , place "
array = string.split(",")
for word in array:
print word
Run Code Online (Sandbox Code Playgroud)
您的方法失败,因为您将其编入索引以从开头到第一个","生成字符串.如果你然后将它从第一个","索引到下一个","并以这种方式遍历字符串,那么这可能会有效.虽然拆分会更好.
字符串有一个split()方法.它返回一个列表:
>>> string = "The , world , is , a , happy , place "
>>> string.split(' , ')
['The', 'world', 'is', 'a', 'happy', 'place ']
Run Code Online (Sandbox Code Playgroud)
如您所见,最后一个字符串上有一个尾随空格.分割这种字符串的一种更好的方法是:
>>> [substring.strip() for substring in string.split(',')]
['The', 'world', 'is', 'a', 'happy', 'place']
Run Code Online (Sandbox Code Playgroud)
.strip() 从字符串的末端剥去空白.
使用for循环打印单词.
| 归档时间: |
|
| 查看次数: |
28518 次 |
| 最近记录: |