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
How to Get the Latest File in a Folder
How to Use Ffmpeg in a Python Function
In Python, How to Check If a String Only Contains Certain Characters
Numpy Import Throws Attributeerror: 'Module' Object Has No Attribute 'Core'
Windowserror: [Error 193] %1 Is Not a Valid Win32 Application in Python
How to Open Excel File Fast in Python
How to Change Milliseconds to Seconds in Python
How to Randomly Partition a List into N Nearly Equal Parts
Pandas: Difference Between Pivot and Pivot_Table. Why Is Only Pivot_Table Working
List of the Most Recently Updated Files in Python
Ioerror: [Errno 32] Broken Pipe When Piping: 'Prog.Py | Othercmd'
Opencv Typeerror: Expected Cv::Umat for Argument 'Src' - What Is This
How to Get Elasticsearch to Perform an Exact Match Query
Django: Get Current User in Model Save
Django: Calling .Update() on a Single Model Instance Retrieved by .Get()