3

I am reading string information as input from a text file and placing them into lists, and one of the lines is like this:

30121,long,Mehtab,10,20,,30

I want to remove the empty value in between the ,, portion from this list, but have had zero results. I've tried .remove() and filter(). Python reads it as a 'str' value.

3
  • 5
    Since it's being read as a string, use a list comprehension to filter out empty values and rejoin: ','.join([i for i in s.split(',') if i]) Commented Jul 19, 2018 at 4:19
  • 1
    As a side note: This is clearly a CSV file, and, depending on where it came from and what kind of data it includes, it might use CSV features like quoting or escaping, in which case just splitting the string won't work. If you're not sure that isn't going to be a problem, you should probably use the csv module. Commented Jul 19, 2018 at 4:43
  • 2
    Also: "I've tried .remove() and filter()" isn't very useful. If you show us the code you tried, we can explain why it's wrong, and how to fix it. If you just tell us that you tried something, but don't show it to us, all we can tell you is that you must have done something wrong—which isn't all that helpful, since you already know that or you wouldn't be asking a question. Commented Jul 19, 2018 at 4:44

4 Answers 4

1
>>> import re
>>> re.sub(',,+', ',', '30121,long,Mehtab,10,20,,30')
'30121,long,Mehtab,10,20,30'
Sign up to request clarification or add additional context in comments.

Comments

0

Use split() and remove()

In [11]: s = '30121,long,Mehtab,10,20,,30'

In [14]: l = s.split(',')

In [15]: l.remove('')

In [16]: l
Out[16]: ['30121', 'long', 'Mehtab', '10', '20', '30']

Comments

0

Filter should work. First I am writing the data in a list and then using filter operation to filter out items in a list which which are empty. In other words, only taking items that are not empty.

data = list("30121","long","Mehtab",10,20,"",30)
filtered_data = list(filter(lambda str: str != '', data))
print(filtered_data)

Comments

0

You can split the string based on your separator ("," for this) and then use list comprehension to consolidate the elements after making sure they are not blank.

",".join([element for element in string.split(",") if element])

We can also use element.strip() as if condition if we want to filter out string with only spaces.

1 Comment

Sorry, was in bit hurry when I originally posted the answer, thought of adding that later on. Done! :bow:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.