-1

here is the sample for string which is inside a list

item_s=["hello - this","is - a","sample - task","i","want - to","do"]

can I have an output like:

item_s=["hello-this","is-a","sample-task","i","want-to","do"]

this is the code i tried to trim the spaces but it was showing error

amount=list(df["Price Range"])
def add_commas(s):
    s1, s2 = s.split('-')

def process(s_part):
    n, tmp_s = len(s_part), []

for i in range(n):
    if i and not i % 3:
        tmp_s.append(',')
    tmp_s.append(s_part[n - i - 1])

return ''.join(tmp_s[::-1])

return process(s1) + '-' + process(s2)

def main():
    amount=list(df["Price Range"])

    return [add_commas(v) for v in amount]

main
deceze
  • 510,633
  • 85
  • 743
  • 889
  • Yes, of course you can. Did you try anything at all? – Sayandip Dutta Feb 25 '21 at 13:07
  • Welcome to StackOverflow! I see you're a new contributor, so I advise you to check out [How to ask a good question](https://stackoverflow.com/help/how-to-ask), [How to create a minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example), and [Why is "Can someone help me?" not an actual question?](https://meta.stackoverflow.com/a/284237/11082165). After reading the links above, please [edit] your question to include your attempts so far, and what precise problem you encounter. – Brian61354270 Feb 25 '21 at 13:07
  • hint: use map you can find the doc about it. – Malo Feb 25 '21 at 13:08
  • look here also: https://stackoverflow.com/questions/3739909/how-to-strip-all-whitespace-from-string – Malo Feb 25 '21 at 13:09
  • i tried using replace function with (" ","") and strip() as loop but none of them is working – Yatin Hasija Feb 25 '21 at 13:14

3 Answers3

3

You can use replace() in list comprehension as:

item_s=["hello - this","is - a","sample - task","i","want - to","do"]
item_s=[item.replace(" ", "") for item in item_s]
print(item_s)
Krishna Chaurasia
  • 8,924
  • 6
  • 22
  • 35
2

Using a list comprehension you can iterate over the items in the list and then replace the spaces with str.replace():

item_s = ["hello - this", "is - a", "sample - task", "i", "want - to", "do"]
item_s = [s.replace(' ', '') for s in item_s]
print(item_s)

Output

['hello-this', 'is-a', 'sample-task', 'i', 'want-to', 'do']

Or you can update in place:

for i, s in enumerate(item_s):
    item_s[i] = s.replace(' ', '')

And to replace all forms of white space which might include spaces, tabs, newlines etc. you can use a regular expression:

import re
item_s = [re.sub(r'\s', '', s) for s in item_s]
mhawke
  • 84,695
  • 9
  • 117
  • 138
1

Of course you can, here is the code :)

You can use a for loop and replace all spaces with the empty string:

item_s=["hello - this","is - a","sample - task","i","want - to","do"]

for s in range(len(item_s)):
    item_s[s] = item_s[s].replace(" ", "")
print(item_s)
Maura Pintor
  • 198
  • 1
  • 14