Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

python - Split by a word (case insensitive)

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']
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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']
>>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...