Search code examples
pythonstringsplitpraw

How to return a word in a string if it starts with a certain character? (Python)


I'm building a reddit bot for practice that converts US dollars into other commonly used currencies, and I've managed to get the conversion part working fine, but now I'm a bit stuck trying to pass the characters that directly follow a dollar sign to the converter.

This is sort of how I want it to work:

def run_bot():
    subreddit = r.get_subreddit("randomsubreddit")
    comments = subreddit.get_comments(limit=25)
    for comment in comments:
        comment_text = comment.body
        #If comment contains a string that starts with '$'
            # Pass the rest of the 'word' to a variable

So for example, if it were going over a comment like this:

"I bought a boat for $5000 and it's awesome"

It would assign '5000' to a variable that I would then put through my converter

What would be the best way to do this?

(Hopefully that's enough information to go off, but if people are confused I'll add more)


Solution

  • You could use re.findall function.

    >>> import re
    >>> re.findall(r'\$(\d+)', "I bought a boat for $5000 and it's awesome")
    ['5000']
    >>> re.findall(r'\$(\d+(?:\.\d+)?)', "I bought two boats for $5000  $5000.45")
    ['5000', '5000.45']
    

    OR

    >>> s = "I bought a boat for $5000 and it's awesome"
    >>> [i[1:] for i in s.split() if i.startswith('$')]
    ['5000']