按单词分割(不区分大小写) [英] Split by a word (case insensitive)

查看:39
本文介绍了按单词分割(不区分大小写)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想拿

我叫 foo bar"

并在 "foo" 上拆分它,并使拆分不区分大小写(在 "foO""FOO" 中的任何一个上拆分>、"Foo" 等),我该怎么办?请记住,虽然我希望拆分不区分大小写,但我也确实希望保持字符串其余部分的区分大小写.

如果我有:

test = "我叫 foo bar"打印 test.split('foo')打印 test.upper().split("FOO")

我会得到

['我的名字是','bar']['我的名字是','酒吧']

分别.

但我想要的是:

['我的名字是','bar']

每次.目标是保持原始字符串的区分大小写,除了我要拆分的内容.

所以如果我的测试字符串是:

hI MY NAME is Foo bar"

我想要的结果是:

['你好我的名字是', 'bar']

解决方案

您可以使用 re.split 函数re.IGNORECASE 标志(或简称 re.I):

<预><代码>>>>进口重新>>>test = "你好,我的名字是 Foo 酒吧">>>re.split("foo", test, flags=re.IGNORECASE)['你好,我的名字是','酒吧']>>>

If I want to take

"hi, my name is foo bar"

and split it on "foo", and have that split be case insensitive (split on any of "foO", "FOO", "Foo", etc), what should I do? Keep in mind that although I would like to have the split be case insensitive, I also DO want to maintain the case sensitivity of the rest of the string.

So if I have:

test = "hi, my name is foo bar"

print test.split('foo')

print test.upper().split("FOO")

I would get

['hi, my name is ', ' bar']
['HI, MY NAME IS ', ' BAR']

respectively.

But what I want is:

['hi, my name is ', ' bar']

every time. The goal is to maintain the case sensitivity of the original string, except for what I am splitting on.

So if my test string was:

"hI MY NAME iS FoO bar"

my desired result would be:

['hI MY NAME iS ', ' bar']

解决方案

You can use the re.split function with the re.IGNORECASE flag (or re.I for short):

>>> import re
>>> test = "hI MY NAME iS FoO bar"
>>> re.split("foo", test, flags=re.IGNORECASE)
['hI MY NAME iS ', ' bar']
>>>

这篇关于按单词分割(不区分大小写)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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