PYTHON Split String at space but keep the spaces - TagMerge
4PYTHON Split String at space but keep the spacesPYTHON Split String at space but keep the spaces

PYTHON Split String at space but keep the spaces

Asked 1 years ago
0
4 answers

I wonder why you need it, but it can be done like so

import re
a = 'bla bla bla bla'
temp = re.sub(' ','\t \t',a)
result = temp.split('\t')

Source: link

0

Python Program
str = '63 41 92 81 69 70'

#split string by single space
chunks = str.split(' ')

print(chunks)
Output
['63', '41', '92', '81', '69', '70']
Python Program
import re

str = '63 41    92  81            69  70'

#split string by single space
chunks = re.split(' +', str)

print(chunks)
Output
['63', '41', '92', '81', '69', '70']
Python Program
import re

str = '63 41\t92\n81\r69 70'

#split string by single space
chunks = str.split()

print(chunks)

Source: link

0

For example, if a string initialized as Hello, World! I am here. exists, splitting it with whitespace as a delimiter will result in the following output.
['Hello,', 'World!', 'I', 'am', 'here.']
For example, let’s use the same string example Hello, World! I am here.. We will use the split() method to separate the string into an array of substrings.
string_list = 'Hello, World! I am here.'.split()

print(string_list)
The output is as expected:
['Hello,', 'World!', 'I', 'am', 'here.']
Let’s modify the previous example to include random leading, trailing, and consecutive whitespaces.
string_list = '      Hello,   World! I am     here.   '.split()

print(string_list)
Output:
['Hello,', 'World!', 'I', 'am', 'here.']

Source: link

0

Example: Consider that there’s a given string as shown in this example below and you need to split it such that the separators/delimiters are also stored along with the word characters in a list. Please follow the example given below to get an overview of our problem statement.
text = 'finxter,practise@Python*1%every day'
somemethod(text)
Desired Output:
['finxter', ',', 'practice', '@', 'Python', '*', '1', '%', 'every', ' ', 'day']
One of the ways in which we can split the given string along with the delimiter is to import the regex module and then split the string using the split() function with the | meta-character.
import re

text = 'fnixter,practice@Python*1%every day'
print(re.split('(\W)', text))
Output
['finxter', ',', 'practice', '@', 'Python', '*', '1', '%', 'every', ' ', 'day']
Let us have a look at the following example to see how this works:
import re

text = 'finxter,practice@Python*1%every day'
print(re.split('([^a-zA-Z0-9])', text))

Source: link

Recent Questions on python

    Programming Languages