如果字符串以某个字符开头,如何 return 字符串中的单词? (Python)

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

我正在构建一个 reddit 机器人用于将美元转换成其他常用货币的练习,我已经设法让转换部分正常工作,但现在我在尝试传递字符时有点卡住了直接跟随转换器的美元符号。

这就是我希望它的工作方式:

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

因此,例如,如果要查看这样的评论:

"I bought a boat for 00 and it's awesome"

它会将“5000”分配给一个变量,然后我将其放入我的转换器

执行此操作的最佳方法是什么?

(希望这些信息足够了,但如果人们感到困惑,我会添加更多)

您可以使用 re.findall 函数。

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

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

如果你用浮点数处理价格,你可以使用这个:

import re

s = "I bought a boat for 00 and it's awesome"

matches = re.findall("$(\d*\.\d+|\d+)", s)
print(matches) # ['5000']

s2 = "I bought a boat for 00.52 and it's awesome"
matches = re.findall("$(\d*\.\d+|\d+)", s2)
print(matches) # ['5000.52']