row = [x.strip() for x in row]
(if you just want to get spaces at the end, use rstrip)
You can use the strip() method to remove trailing and leading spaces:
>>> s = ' abd cde '
>>> s.strip()
'abd cde'
Note: the internal spaces are preserved.
Should be noted that strip() method would trim any leading and trailing whitespace characters from the string (if there is no passed-in argument). If you want to trim space character(s), while keeping the others (like newline), this answer might be helpful:
sample = ' some string\n'
sample_modified = sample.strip(' ')
print(sample_modified) # will print 'some string\n'
strip([chars]): You can pass in optional characters to strip([chars]) method. Python will look for occurrences of these characters and trim the given string accordingly.
Python: Removing spaces from list objects - Stack Overflow
json - Remove leading and trailing spaces from a Python list - Stack Overflow
python - Delete Extra Space from Values In List - Stack Overflow
python removing whitespace from string in a list - Stack Overflow
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]
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
For your case, with a list, you can use str.strip()
l = [x.strip() for x in List]
This will strip both trailing and leading spaces. If you only need to remove leading spaces, go with Alex' solution.
Use str.lstrip here, as the white-space is only at the front:
List = [s.lstrip() for s in List]
# ['5432', '23421', '43242', ...]
Or in this case, seeing as you know how many spaces there are you can just do:
List = [s[1:] for s in List]
You're forgetting to reset j to zero after iterating through the first list.
Which is one reason why you usually don't use explicit iteration in Python - let Python handle the iterating for you:
>>> networks = [[" kjhk ", "kjhk "], ["kjhkj ", " jkh"]]
>>> result = [[s.strip() for s in inner] for inner in networks]
>>> result
[['kjhk', 'kjhk'], ['kjhkj', 'jkh']]
This generates a new list:
>>> x = ['a', 'b ', ' c ']
>>> map(str.strip, x)
['a', 'b', 'c']
>>>
Edit: No need to import string when you use the built-in type (str) instead.