python - 如何返回字符串中以某个字符开头的单词? (Python)

标签 python string split praw

我正在构建一个 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 $5000 and it's awesome"

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

最好的方法是什么?

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

最佳答案

您可以使用re.findall功能。

>>> 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']

或者

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

关于python - 如何返回字符串中以某个字符开头的单词? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29665859/

相关文章:

python - TinyCSS 和 GTK 主题 @define-color

python - 鉴于要分配的值是非数字,如何将数据框从长更改为宽?

c++ - 如何在 C++ 中使用类似 shell 的规则拆分字符串?

python - 在没有多重索引的情况下分割 Pandas 系列

Python+OpenCV : cv2. 写入

python - 在 Pandas 中如何使用 drop_duplicates 有一个异常(exception)?

python - 在 python 中搜索给定字符串的超字符串列表的最快方法

java - 如何使用 String 方法打印对象值

java - 如何从特定格式的字符串中提取数字?

c++ - 如何去掉 QString 中的括号及其内容?