Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Split function
#1
Hello dear users, iam using import re function to split my strings. For example i want to split characters +,- and string is "50+50-50" i get output ['50', '50', '50']. Is it possible to know if "-" or "+" was splitted and where ? Or is it possible to get output also with theese splitted characters ? So something like ['50','+','50', '-', '50']

here is code
import re

calc = "50+50-50"
answer = re.split('\*|\-|\+|\/',calc)


print(answer)
Reply
#2
Use a group to capture the splitting pattern too. Also, it is better to use raw strings with regexes to prevent interpretation of the backslash
>>> calc = "50+50-50"
>>> answer = re.split(r'(\*|\-|\+|\/)',calc)
>>> answer
['50', '+', '50', '-', '50']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [split] Creating a variable as a function DPaul 23 6,669 Sep-07-2020, 05:20 PM
Last Post: DPaul
  Help me to using split function SukhmeetSingh 4 2,920 May-19-2019, 11:32 PM
Last Post: DeaD_EyE
  How to split a string containing function calls? Metalman488 4 2,876 Oct-27-2018, 06:50 PM
Last Post: Metalman488

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020