user12904074
user12904074

Reputation:

how we can split a data input where some of them are separated by one space and some with 2 space?

I have a data input as below:

[-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914]
[ 228 -114 -114  914  228 -114 -114  228  228 -114 -114  228  228 -114 -114]

as you can see there is 1 space before negative numbers and 2 spaces before positive.

I read file as this :

def switch(letter):
    switcher = {
        "[": "",
        "]": "",
        "\n": "@",
    }
    return switcher.get(letter, letter)


converted_data = ''
with open("/Users/naghmeh/Documents/python/core1", "r") as file:
    data = file.read()

for letter in data:
    letter = switch(letter)
    converted_data = converted_data+letter

converted_data = converted_data.split('@')
split_converted_data = []
for i in converted_data:
    i = i.split(" ")
    split_converted_data.append(i)  

which i = i.split(" ") separate by 1 space. so code can not be run correctly. how I can fix it?

Upvotes: 1

Views: 49

Answers (3)

Jona
Jona

Reputation: 1288

In the split documentation, you can find :

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

So, use split() without indicating the separator.

"-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914".split()

Upvotes: 3

Guy
Guy

Reputation: 50899

Use split() with no arguments

a = '-114 -114  228 -114  228  228 -114 -114  228  228 -114  228 -114 -114  914'
a = a.split()
print(a)
# ['-114', '-114', '228', '-114', '228', '228', '-114', '-114', '228', '228', '-114', '228', '-114', '-114', '914']

Upvotes: 3

Thomas Schillaci
Thomas Schillaci

Reputation: 2453

You can do:

for i in converted_data:    
    i = i.replace('  ', ' ').split(' ')
    split_converted_data.append(i) 

To replace every pair of space by only one

Upvotes: 0

Related Questions