Stripping Whitespaces from a List Inside the List of Tuples

Stripping whitespaces from a list inside the list of tuples?

for tup in features:
lst = [i.strip() for i in tup[1]]
tup = tup[0] + lst

If I understand correctly, this will iterate over each tuple in your list, and replace the list - index 1 - with a str.strip() versin for each item

Strip spaces from a list of tuples

Version 3

You can use a list comprehension with ','.join. Use str.replace to remove spaces after the join is complete.

In [86]: [','.join(y).replace(' ', '')  for y in lst]
Out[86]: ['Parrish,Alabama', 'PhilCampbell,Alabama', 'Lisman,Alabama']

Readability improved thanks to no1xsyzy and Jon Clements.

python removing whitespace from string in a 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']]

getting rid of some elements that contain just white space in a list

use str.strip() and a simple list comprehension:

In [31]: lis=[' ',' ',' ',' ', '12 21','12 34']

In [32]: [x for x in lis if x.strip()]
Out[32]: ['12 21', '12 34']

or using filter():

In [37]: filter(str.strip,lis)
Out[37]: ['12 21', '12 34']

This works because for empty strings:

In [35]: bool(" ".strip())
Out[35]: False

help(str.strip):

In [36]: str.strip?
Type: method_descriptor
String Form:<method 'strip' of 'str' objects>
Namespace: Python builtin
Docstring:
S.strip([chars]) -> string or unicode

Return a copy of the string S with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping


Related Topics



Leave a reply



Submit