Tutorial :Python: How do i manipulate the list to get the string starting with '+'?


I am comparing 2 txt files that are ls -R of the etc directory in a linux system. I compared the 2 files using difflib.differ and got this list as my result (i put the dots to keep the list short in here):

result = [' etc:\n', ' ArchiveSEL\n', ' HOSTNAME\n', ' RMCPUser\n', ...,      ' qcleaner\n', '+ extraFile\n', ' rc.d\n', '+ extraFile2\n', ...,      ' resolv.conf\n', ' wu-ftpd\n']  

I want to be able to take the strings with the '+' sign out to do something else. how do i manipulate the list? in the example above, i want to be able to get this string "extraFile" and "extraFile2".

Thanks to all the people who posted solutions. It helps a lot and I am grateful :)

Here's what I did to get the string I wanted:

newresult = [file[2:-1] for file in result if file.startswith('+')]

to print out the strings:

for i in range (len(newresult)):
print newresult[i]

THANKS~!!! :)


You can use list comprehension:

newlist = [file[1:] for file in result if file.startswith('+')]  #            ^-- gets rid of `+` at the beginning  

See the string methods documentation.

And if you want to get rid of the newline character and whitespaces just do:

newlist = [file[1:].strip() for file in result if file.startswith('+')]  

Another way would be to use filter(), but you cannot manipulate the string then (just want to mention it for completeness):

newlist = filter(lambda s: s.startswith('+'), result)  


>>> [x.strip('+').strip() for x in result if x.startswith("+")]  ['extraFile', 'extraFile2']  

Improved version with stripping out '+' and whitespace/linebreaks


Try a list comprehension : [x for x in result if x[0]=='+']

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »