python根据分隔符查找子字符串 [英] python find substrings based on a delimiter

查看:44
本文介绍了python根据分隔符查找子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Python, so I might be missing something simple.

我举了一个例子:

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

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

I have to create substrings separated by , and print them and process instances separately. That means in this example I should be able to print

The 
world 
is 
a
happy 
place

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

What approach can I take? I was trying to use the string find functionality, but

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

无助于查找第二个、第三个实例.

does not help in finding 2nd, 3rd instances.

推荐答案

尝试使用 split 功能.

在您的示例中:

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

您的方法失败了,因为您对其进行了索引以产生从头到第一个,"的字符串.如果您然后将它从第一个,"索引到下一个,"并以这种方式遍历字符串,这可能会起作用.不过拆分会好很多.

Your approach failed because you indexed it to yield the string from beginning until the first ",". This could work if you then index it from that first "," to the next "," and iterate across the string that way. Split would work out much better though.

这篇关于python根据分隔符查找子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆