Jump to content

Split string at a space or "," in python

Go to solution Solved by Slottr,

You would use regex, like this:

 

import re
mystring = input()
re.split(r'[\s,]+', mystring)

 

You would use regex, like this:

 

import re
mystring = input()
re.split(r'[\s,]+', mystring)

 

Community Standards || Tech News Posting Guidelines

---======================================================================---

CPU: R5 3600 || GPU: RTX 3070|| Memory: 32GB @ 3200 || Cooler: Scythe Big Shuriken || PSU: 650W EVGA GM || Case: NR200P

Link to post
Share on other sites

Bear in mind that the \s in RegEx captures more than just spaces.  It also gets new lines (\n), carriage returns (\r), vertical whitespace (\v), form feed (\f), and tabs (\t).  You can put a space inside the square brackets (denotes a set of characters to accept) to only accept a space or a comma.  The + after the square brackets means that it will accept one or many of those characters, so if your string has multiple spaces, it'll result in the array elements having no spaces or commas, and will also prevent empty or null elements from making their way into the array.  A site I use often when I need to check RegEx strings is https://www.regex101.com

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×