Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, Remove word start with specific character

Tags:

python

How can I remove a word that starts with a specific char in python?

e.g..

string = 'Hello all please help #me'

I want to remove the word that starts with #

the result I want is:

Hello all please help 
like image 310
A guy Avatar asked Nov 28 '14 20:11

A guy


1 Answers

>>> a = "Hello all please help #me "
>>> filter(lambda x:x[0]!='#', a.split())
['Hello', 'all', 'please', 'help']

you can join it using whitespace:

>>> " ".join(filter(lambda x:x[0]!='#', a.split()))
'Hello all please help'

let me explain you step by step:

>>> a = "Hello all please help #me "
>>> a.split()                          # split, splits the string on delimiter, by default its whitespace
['Hello', 'all', 'please', 'help', '#me']
>>> >>> filter(lambda x:x[0]!='#', a.split())
['Hello', 'all', 'please', 'help']

filter return only those element for which condition is True.

like image 110
Hackaholic Avatar answered Oct 31 '22 17:10

Hackaholic