I want to split my string into pieces but every some text and a special character. I have a string:
str = "ImEmRe@b'aEmRe@b'testEmRe@b'string"
I want my string to be split every EmRe@b'
characters as you can see it contais the '
and that's the problem.
I tried doing re.split(r"EmRe@b'\B", str)
, re.split(r"EmRe@b?='\B", str)
and also I tried both of them but without the r
before the pattern. How do I do it? I'm really new to regular expressions. I would even say I've never used them.
Asked
Active
Viewed 498 times
2

Qiasm
- 356
- 6
- 15
-
Do you want to make sure there is a word char after `'`? Then just use `re.split(r"EmRe@b'\b", text)` – Wiktor Stribiżew Oct 04 '19 at 21:43
-
It's not a duplicate. As you can see, I've chosen the best answer and if you don't know what I meant in the question then look at the answer and you will realize that It's not a duplicate :). – Qiasm Oct 05 '19 at 22:05
-
This is duplicate because you need to remove `\B` and your pattern would work. All you need to know is what `\B` is, and that is what the linked post is about. – Wiktor Stribiżew Oct 05 '19 at 22:07
-
Removing `\B` didn't work. The marked answer worked. – Qiasm Oct 07 '19 at 06:11
-
[Can't find any difference in output](https://ideone.com/Qfgrit) – Wiktor Stribiżew Oct 07 '19 at 07:10
1 Answers
1
Firstly, change the name of your variable, since str()
is a built-in Python function.
If you named your variable word
, you could get a list of elements split by your specified string by doing this:
>>> word = "ImEmRe@b'aEmRe@b'testEmRe@b'string"
>>> word
"ImEmRe@b'aEmRe@b'testEmRe@b'string"
>>> word.split("EmRe@b'")
['Im', 'a', 'test', 'string']
Allowing you to use them in many more ways than just a string! It can be saved to a variable, of course:
>>> foo = word.split("EmRe@b'")
>>> foo
['Im', 'a', 'test', 'string']

peki
- 669
- 7
- 24
-
Thanks! Works perfectly. Why it does not work with regular expressions though? – Qiasm Oct 04 '19 at 22:57
-
Wouldn't know... I don't use it as much since raw Python does it for me faster and easier... – peki Oct 07 '19 at 07:30