Strings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:
for i in hello:
j = i.replace(' ','')
k.append(j)
However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:
hello = [x.strip(' ') for x in hello]
Answer from Mark Byers on Stack OverflowStrings in Python are immutable (meaning that their data cannot be modified) so the replace method doesn't modify the string - it returns a new string. You could fix your code as follows:
for i in hello:
j = i.replace(' ','')
k.append(j)
However a better way to achieve your aim is to use a list comprehension. For example the following code removes leading and trailing spaces from every string in the list using strip:
hello = [x.strip(' ') for x in hello]
List comprehension [num.strip() for num in hello] is the fastest.
>>> import timeit
>>> hello = ['999 ',' 666 ']
>>> t1 = lambda: map(str.strip, hello)
>>> timeit.timeit(t1)
1.825870468015296
>>> t2 = lambda: list(map(str.strip, hello))
>>> timeit.timeit(t2)
2.2825958750515269
>>> t3 = lambda: [num.strip() for num in hello]
>>> timeit.timeit(t3)
1.4320335103944899
>>> t4 = lambda: [num.replace(' ', '') for num in hello]
>>> timeit.timeit(t4)
1.7670568718943969
how to remove white spaced from a nested list
Removing space from list items
python - How to remove all spaces in the strings in list - Stack Overflow
How to remove extra space from output list tuple?
hi, I have made a list already but wanted to remove the blank spaces from each index of my nested list. the list is pretty long so I will add a small version of it below.
list1 = [[' CITS2224-1 ', ' CITS2023-2 ', ' CITS3221-2 ', ' CITS3224-1 ', ' CITS3225-1 '], [' CITS2023-2 ', ' ENSC3221-2 ', ' ENSC3224-1 ', ' ENSC3225-1 ', ' ENSC3227-2 ', ' ENSC3210-1 ', ' ENSC3221-1 ', ' MECH3023-2 '], [' CITS1021-2 ', ' CITS2021-1 ', ' CITS2023-2 ', ' ENSC2224-1 ', ' ENSC3211-2 ', ' ENSC3213-2 ', ' MATH2221-1 ', ' STAT1524-1 ']
there is a space in front and after each index of the string and I want to remove it. for example the first index being 'CITS224-1'. I have tried looping through the entire list and using the replace function however that is messing with the design of the list. I want to leave the way that the list is nested untouched only want to remove the blank space before and after
thanks for any help
So let’s say I have a list of items where there is a space in front of every item like so: [‘ 2’, ‘ 4’, ‘ 8’]
How can I remove the blank spaces from each item? All the info I’ve found online refers to the list items themselves and not the actual content of the items.
You could use a list comprehension:
new_list = [elem for elem in mylist if elem.strip()]
Using strip() guarantees that even strings containing only multiple spaces will be removed.
Use filter with unbound method str.strip.
Python 2.x
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> filter(str.strip, mylist)
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
Python 3.x
>>> mylist=[ " ","abc","bgt","llko"," ","hhyt"," "," ","iuyt"]
>>> list(filter(str.strip, mylist))
['abc', 'bgt', 'llko', 'hhyt', 'iuyt']
I think you are conflating the list and the representation of the list. The list itself doesn't have spaces, or even commas, it just has the items (in your case, the numbers). The representation of the list is just that - a way to represent the data inside of it in a normal, standard way. That standard includes commas and spaces.
If you want a new thing that represents the list and its items in the way you are saying, you can do that by making a new string just like that.
str(numbers).replace(' ','')
This has two functions in it, chained together. First, we do str(numbers) to get a string that is the string-representation of the list. This will be the string '[1, 2, 3, 4, 5]'. Then you replace any blank space-bar ' ' with nothing ''.
Edit:
I think I read your question too quickly and see that you did the exact same as what I have in my code here and said it isn't doing exactly what you want to do. I think the answer here is: no.
As I say in my first paragraph, there is the list and there is the lists representation. The function for the list's representation is a python built-in that can not be trivially overridden. I'm not saying it can't be done, but I don't think you'll get it done without defining some new things.
You can change the print behavior of the list to something you code yourself.
numbers = input().split(',')
for i in range(0, len(numbers)):
numbers[i] = int(numbers[i])
mylist = str(numbers).replace(' ','')
print('[' + ','.join([str(n) for n in numbers]) + ']')
This prints a bracket [, then each number separated by commas without any spaces, and finally the ending bracket ].
Output looks like this:
1, 2, 3, 4, 5
[1,2,3,4,5]
In your for loop, change f to f.replace(' ',''). That will remove spaces.
This code should work:
val = []
for c in f.replace(' ',''):
val.append(ord(c))
val = [w - 5 if w > 20 else w for w in val]
From c in f and ord(c) I am assuming f is a str. The if c filter eliminates spaces.
codes = (ord(c) for c in f if c)
# codes is a genex. Now you can use it any way you want, e.g
codes_ = [code-5 if code > 20 else code for code in codes]
The strip() method will strip all the characters from the end of the string. In your case, strip starts at the end of your string, encounters a '\n' character, and exits.
It seems a little unclear what you are trying to do, but I will assume that you are looking to clear out any white space between the last non-whitespace character of your string and the newline. Correct me if I'm wrong.
There are many ways to do this, and this may not be the best, but here is what I came up with:
m = ['This, is a string. \n', 'another string! \n', 'final example\n ']
m = map(lambda(x): x.rstrip() + '\n' if x[-1] == '\n' else x.rstrip(' '), m)
print(m)
['This, is a string.\n', 'another string!\n', 'final example\n']
Here I use the built in map function iterate over each list element and remove all white space from the end (rstrip() instead of strip() which does both the start and end) of the string, and add in a new line if there was one present in the original string.
Your code wouldn't be useful in a script; you are just seeing the REPL displaying the result of the expression i.strip(' '). In a script, that value would just be ignored.
To create a list, use a list comprehension:
result = [i.strip(' ') for i in m if ' ' in i]
Note, however, strip only removes the requested character from either end; in your data, the space precedes the newline. You'll need to do something like removing the newline as well, then put it back:
result = ["%s\n" % i.strip() for i in m if ' ' in i]
You could use a list comprehension here with rstrip():
items = [' apple ', 'banana ', 'orange ']
output = [x.rstrip() for x in items]
print(output) # [' apple', 'banana', 'orange']
Just create a new list and use list comprehension. Iterate through each element, check if it has space at the end of the element. If it does, remove it and append it to a new list.
items = [' apple ', 'banana ', 'orange ']
newList = [x[:-1] for x in items if x[-1] == ' ']
print(newList)
output
[' apple', 'banana', 'orange']
Say that I have a list with the elements:
listA = ['a','b','c','d',' ','f','g']
Is there a way to just remove (not replace) the space in-between the d and the f?