0

I have a list with spaces within the string. How can I remove these spaces.

['ENTRY', '      102725023         CDS       T01001']

I would like to have the final list as:

['ENTRY', '102725023 CDS T01001']

I tried the strip() function but the function is not working on list. Any help is highly appreciated.Remo

3 Answers 3

1

Suppose this is you string

string = "A     b       c   "

And you want it in this way

Abc

What you can do is

string2 = " ".join(string.split())
print(string2)
Sign up to request clarification or add additional context in comments.

4 Comments

It is a list element, will that work on that?
Just iterate over it @rshar
I don't think so, but you can use str(list). Although it will work fine but it will print all the strings in list with the brackets and commas.
It will work fine. I tried it.
1

The easiest way is to build a new list of the values with the spaces removed. For this, you can use list comprehensions and the idiom proposed by @CodeWithYash

old_list = ['ENTRY', '      102725023         CDS       T01001']
new_list = [" ".join(string.split()) for s in old_list]

Note that this works because the default behavior of split is:

split according to any whitespace, and discard empty strings from the result.

If you would want to remove anything but whitespace, you would have to implement you own function, maybe using regular expression.

Note also that in Python strings are immutable: you can not edit each item of the list in place. If you do not want to create a new list (for example, if a reference to the list is kept in other place of the program), you can change every item:

l = ['ENTRY', '      102725023         CDS       T01001']
for i, s in enumerate(l):
    old_list[i] = " ".join(s.split())
print(l)

Output:

['ENTRY', '102725023 CDS T01001']

Comments

0

I wrote this function:

s = "   abc       def     xyz    "
def proc(s):
    l = len(s)
    s = s.replace('  ',' ')
    while len(s) != l:
        l = len(s)
        s = s.replace('  ',' ')
    if s[0] == ' ':
        s = s[1:]
    if s[-1] == ' ':
        s = s[:-1]
    return s
print(proc(s))

the idea is to keep replacing every two spaces with 1 space, then check if the first and last elements are also spaces I don't know if there exists an easier way with regular expressions or something else.

2 Comments

AttributeError: 'list' object has no attribute 'replace'.. It is a list
Then just apply this method to each element in the list

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.