I have the following line.
words = "this is a book and i like it"
What I want is that when I split it into one space, I get the following. wordList = words.split(" ") print wordList << ['this','is','a',' book','and','i',' like','it']
wordList = words.split(" ") print wordList << ['this','is','a',' book','and','i',' like','it']
A simple function words.split(" ")splits the string, but with double space, it removes both spaces, which gives 'book'and 'like'. and I need to ' book', and ' like'kept the extra spaces in the output split in the case of double, triple ... n spaces
words.split(" ")
'book'
'like'
' book'
' like'
: char, \s? , + + .
\s?
: rstrip , , .
rstrip
import re words = "this is a book and i like it" print(re.findall(r'\s?(\s*\S+)', words.rstrip())) # => ['this', 'is', 'a', ' book', 'and', 'i', ' like', 'it']
. Python. re.findall , , .
re.findall
, ββ- regex. :
?
(\s*\S+)
\s*
*
\S+
+
, , (? < =) :
import re re.split("(?<=\\S) ", words) # ['this', 'is', 'a', ' book', 'and', 'i', ' like', 'it']
:
re.split("(?<!\\s) ", words) # ['this', 'is', 'a', ' book', 'and', 'i', ' like', 'it']
If you do not want to use a regular expression and want to keep something close to your own code, you can use something like this:
words = "this is a book and i like it" wordList = words.split(" ") for i in range(len(wordList)): if(wordList[i]==''): wordList[i+1] = ' ' + wordList[i+1] wordList = [x for x in wordList if x != ''] print wordList # Outputs: ['this', 'is', 'a', ' book', 'and', 'i', ' like', 'it']
List comprehension alternative:
word_list = iter(words.split(" ")) ["".join([" ", next(word_list)]) if not w else w for w in word_list] # ['this', 'is', 'a', ' book', 'and', 'i', ' like', 'it']
Source: https://habr.com/ru/post/1676912/More articles:Is it possible to use inline css functions in sass? - cssdynamically allocated array size in C - cHow to update tag text via onclick event in ASP.net (Razor)? - c #Trying to understand URLSession data caching - iosDoes SSH.NET only support the OpenSSH private key? If not, what are the limitations? - c #How to use custom passwords to validate django authentication passwords? - pythonWhy can I register an OutOfMemory error in java? - javaNUnit 2016 Throws.TypeOf - c #Index Of Bounds on List.Contains - c #How to group a common element in an array? - apache-sparkAll Articles