使用多字符分隔符拆分字符串 [英] Split string with multiple-character delimiter

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

问题描述

假设我有以下字符串:

"你好.我叫弗雷德.我今年 25.5 岁."

我想把它分成句子,这样我就有了以下列表:

[你好",我叫弗雷德",我今年 25.5 岁"]

如您所见,我想在字符串 " 的所有出现处拆分字符串.",没有出现任何".""".Python 的 str.split() 在这种情况下不起作用,因为它会将字符串的每个字符视为单独的分隔符,而不是将整个字符串视为多字符分隔符.有没有简单的方法可以解决这个问题?

解决方案

为我工作

<预><代码>>>>你好.我叫弗雷德.我今年 25.5 岁.".split(".")['你好','我的名字是 Fr.ed','我 25.5 岁.']

say I have the following string:

"Hello there. My name is Fred. I am 25.5 years old."

I want to split this into sentences, so that I have the following list:

["Hello there", "My name is Fred", "I am 25.5 years old"]

As you can see, I want to split the string on all occurrences of the string ". ", not any occurrence of either "." or " ". Python's str.split() will not work in this case because it will treat each character of the string as a separate delimiter, rather than the whole string as a multi-character delimiter. Is there a simple way to solve this problem?

解决方案

Works for me

>>> "Hello there. My name is Fr.ed. I am 25.5 years old.".split(". ")
['Hello there', 'My name is Fr.ed', 'I am 25.5 years old.']

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

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