Reputation: 570
I'm trying to preprocess message data from the StockTwits API, how can I remove all instances of $name from a string in python?
For example if the string is:
$AAPL $TSLA $MSFT are all going up!
The output would be:
are all going up!
Upvotes: 1
Views: 47
Reputation: 2645
I'm not sure I get it, but If I'm to remove all instances of words that start with $
, I would break into individual strings, then look for $
, and re-form using a list comprehension.
substrings = string.split(' ')
substrings = [s for s in substrings if not s.startswith('$')]
new_string = ' '.join(substrings)
Some would use regular expressions, which are likely more computationally efficient, but less easy to read.
Upvotes: 1
Reputation: 117661
Something like this would do:
>>> s = "$AAPL $TSLA $MSFT are all going up!"
>>> re.sub(r"\$[a-zA-Z0-9]+\s*", "", s)
'are all going up!'
This allows numbers in the name as well, remove 0-9
if that's not what you want (it would remove e.g. $15
as well).
Upvotes: 2