Is there a function in Python to split a string without ignoring the spaces?

Is there a function in Python to split a string without ignoring the spaces in the resulting list?

E.g:

s="This is the string I want to split".split()

gives me

>>> s
['This', 'is', 'the', 'string', 'I', 'want', 'to', 'split']

I want something like

['This',' ','is',' ', 'the',' ','string', ' ', .....]


Asked by: Aston616 | Posted: 27-01-2022






Answer 1

>>> import re
>>> re.split(r"(\s+)", "This is the string I want to split")
['This', ' ', 'is', ' ', 'the', ' ', 'string', ' ', 'I', ' ', 'want', ' ', 'to', ' ', 'split']

Using the capturing parentheses in re.split() causes the function to return the separators as well.

Answered by: Sophia688 | Posted: 28-02-2022



Answer 2

I don't think there is a function in the standard library that does that by itself, but "partition" comes close

The best way is probably to use regular expressions (which is how I'd do this in any language!)

import re
print re.split(r"(\s+)", "Your string here")

Answered by: Roman820 | Posted: 28-02-2022



Answer 3

Silly answer just for the heck of it:

mystring.replace(" ","! !").split("!")

Answered by: Daryl647 | Posted: 28-02-2022



Answer 4

The hard part with what you're trying to do is that you aren't giving it a character to split on. split() explodes a string on the character you provide to it, and removes that character.

Perhaps this may help:

s = "String to split"
mylist = []
for item in s.split():
    mylist.append(item)
    mylist.append(' ')
mylist = mylist[:-1]

Messy, but it'll do the trick for you...

Answered by: Julian927 | Posted: 28-02-2022



Similar questions

python - Is there a function that could find slope of a curve ignoring peaks?

Let's say I obtained a timeserie (in blue) (with some missing data) that is (as far as i understood) : - following a general trend between specific points - more or less cyclic I have drawn the red curve myself. I need to find a way to obtain it in realtime


python - Where function ignoring Nan

I am trying to use the where function while ignoring Nan, I do not wish to drop or replace the Nans. Here a toy data set: df=pd.DataFrame({ 'A':[8,39,40,52], 'B':[8,39,np.nan,50], }) Which gives: A B 0 8 8.0 1 39 39.0 2 40 NaN 3 52 50.0 Desired result: A B ...


Execute function body ignoring certain lines without comments (Python)?

I have a couple of functions written in a single Python file. They perform a sequence of steps on a file-based dataset. My workflow: After I finished coding a part of the function's body, I run the function to see how it goes. It may break at a certain point. I fix the code and re-run the function. The problem is that when I re-run the function, it will execute the lines that...


string - How to run a function while ignoring several lines in Python?

I have a file that looks like this: a b str1 c d str2 e f Now I want to run a re.sub() function that applies to lines in this file except lines between "str1" and "str2" (i.e. only apply to line "a", "b", "e" and "f"). How should I do this? Thanks!


python - Is there a function that could find slope of a curve ignoring peaks?

Let's say I obtained a timeserie (in blue) (with some missing data) that is (as far as i understood) : - following a general trend between specific points - more or less cyclic I have drawn the red curve myself. I need to find a way to obtain it in realtime


Python, print function ignoring ANSI color commands

I have a similar problem as explained in this post ANSI escape code wont work on python interpreter I am using Macbook Pro and Python 3.7.0. When I give a print command with ANSI commands it prints the characters rather than take effect >>> print ('\033[1;32;48m hello') [1;32;48m hello...


python - Where function ignoring Nan

I am trying to use the where function while ignoring Nan, I do not wish to drop or replace the Nans. Here a toy data set: df=pd.DataFrame({ 'A':[8,39,40,52], 'B':[8,39,np.nan,50], }) Which gives: A B 0 8 8.0 1 39 39.0 2 40 NaN 3 52 50.0 Desired result: A B ...


Is there a common way to check in Python if an object is any function type?

I have a function in Python which is iterating over the attributes returned from dir(obj), and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use callable() for this, but I don't want to include classes. The best I've come up with so far is: isinstance(obj, (types.BuiltinFunctionType, types.FunctionTy...


python - Which is more pythonic, factory as a function in a module, or as a method on the class it creates?

I have some Python code that creates a Calendar object based on parsed VEvent objects from and iCalendar file. The calendar object just has a method that adds events as they get parsed. Now I want to create a factory function that creates a calendar from a file object, path, or URL. I've been using the iCalendar python module, w...


Is there a function in python to split a word into a list?

This question already has answers here:


unicode - Python: Use the codecs module or use string function decode?

I have a text file that is encoded in UTF-8. I'm reading it in to analyze and plot some data. I would like the file to be read in as ascii. Would it be best to use the codecs module or use the builtin string decode method? Also, the file is divided up as a csv, so could the csv module also be a valid solution? Thanks for your help.


How do I get the name of a function or method from within a Python function or method?

I feel like I should know this, but I haven't been able to figure it out... I want to get the name of a method--which happens to be an integration test--from inside it so it can print out some diagnostic text. I can, of course, just hard-code the method's name in the string, but I'd like to make the test a little more DRY if possible.


Lambda function for classes in python?

There must be an easy way to do this, but somehow I can wrap my head around it. The best way I can describe what I want is a lambda function for a class. I have a library that expects as an argument an uninstantiated version of a class to work with. It then instantiates the class itself to work on. The problem is that I'd like to be able to dynamically create versions of the class, to pass to the library, but I can't figur...


function pointers in python

I would like to do something like the following: def add(a, b): #some code def subtract(a, b): #some code operations = [add, subtract] operations[0]( 5,3) operations[1](5,3) In python, is it possible to assign something like a function pointer?


python - Django foreign key access in save() function

Here's my code: class Publisher(models.Model): name = models.CharField( max_length = 200, unique = True, ) url = models.URLField() def __unicode__(self): return self.name def save(self): pass class Item(models.Model): publisher = models.ForeignKey(Publisher) name = models.CharField( max_...


python - make a parent function return - super return?

there is a check I need to perform after each subsequent step in a function, so I wanted to define that step as a function within a function. >>> def gs(a,b): ... def ry(): ... if a==b: ... return a ... ... ry() ... ... a += 1 ... ry() ... ... b*=2 ... ry() ... >>> gs(1,2) # should return 2 >>> gs(1,1) # should return 1 >>> gs(5,3) # should return 6...


python - Safe escape function for terminal output

I'm looking for the equivalent of a urlencode for terminal output -- I need to make sure that garbage characters I (may) print from an external source don't end up doing funky things to my terminal, so a prepackaged function to escape special character sequences would be ideal. I'm working in Python, but anything I ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top