如何在特殊字符后找到 python 中的第 n 个数据?

How to find nth data in python after special char?

我有一个文件,其中包含行中的一些信息。我只想打印 最后一个字符 ∑ 之后的单词。 我该怎么做?

正文:

App∑Category∑Rating∑Reviews∑Size∑Installs∑Type∑Price∑Content Rating∑Genres∑Last Updated∑Current Ver∑Android Ver
Photo Editor & Candy Camera & Grid & ScrapBook∑ART_AND_DESIGN∑4.1∑159∑19M∑10,000+∑Free∑0∑Everyone∑Art & Design∑7-Jan-18∑1.0.0∑4.0.3 and up
Coloring book moana∑ART_AND_DESIGN∑3.9∑967∑14M∑500,000+∑Free∑0∑Everyone∑Art & Design;Pretend Play∑15-Jan-18∑2.0.0∑4.0.3 and up

代码:

def mapper(_, line):
    words = line.split('∑')

结果: [4.0.3 及更高版本,4.0.3 及更高版本]

您可以只使用索引 [-1],如下所示:

def mapper(_, line):
    words = line.split('∑')
    print(words[-1])

一个有效的方法是使用 rsplit 和 maxsplit 为 1,并取最后一项:

def mapper(_, line):
    last = line.rsplit('∑', maxsplit=1)[-1]

请注意,如果行中没有拆分字符,这将默认为整行。

如果要确保拆分有效:

def mapper(_, line):
    chunks = line.rsplit('∑', maxsplit=1)
    last = chunks[1] if len(chunks)==2 else None # or other default value