python根据分隔符查找子字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18808707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 11:55:31  来源:igfitidea点击:

python find substrings based on a delimiter

pythonregexstring

提问by MAG

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

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

I am given an example:

我举了一个例子:

 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.

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

采纳答案by DHandle

Try using the splitfunction.

尝试使用该split功能。

In your example:

在你的例子中:

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.

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

回答by flornquake

Strings have a split()method for this. It returns a list:

字符串split()对此有一个方法。它返回一个列表:

>>> string = "The , world , is , a , happy , place "
>>> string.split(' , ')
['The', 'world', 'is', 'a', 'happy', 'place ']

As you can see, there is a trailing space on the last string. A nicer way to split this kind of string would be this:

如您所见,最后一个字符串上有一个尾随空格。拆分这种字符串的更好方法是:

>>> [substring.strip() for substring in string.split(',')]
['The', 'world', 'is', 'a', 'happy', 'place']

.strip()strips whitespace off the ends of a string.

.strip()从字符串的末端去除空格。

Use a forloop to print the words.

使用for循环打印单词。

回答by hwnd

Another option:

另外一个选项:

import re

string = "The , world , is , a , happy , place "
match  = re.findall(r'[^\s,]+', string)
for m in match:
    print m

Output

输出

The
world
is
a
happy
place

See a demo

演示

You could also just use match = re.findall(r'\w+', string)and you will get the same output.

您也可以直接使用match = re.findall(r'\w+', string),您将获得相同的输出。

回答by Escualo

Simple thanks to the convenient string methods in Python:

简单得益于 Python 中方便的字符串方法:

print "\n".join(token.strip() for token in string.split(","))

Output:

输出:

The
world
is
a
happy
place

By the way, the word stringis a bad choice for variable name (there is an stringmodule in Python).

顺便说一句,这个词string对于变量名来说是一个糟糕的选择(stringPython 中有一个模块)。