簡體   English   中英

Python正則表達式:只找到匹配'.+'的變量值

[英]Python regex: find only the variable value matching '.+'

我編寫了以下程序來計算分數。 他們是僅找到標記的更好方法。

import re

string = """
Q1
|-->1
|-->1
|-->1
|-->1
|-->1
"""
pattern = '>.+\n'

result = re.findall(pattern, string)
marks = 0
for x in result:
    marks += int(x.replace('>', '').replace('\n', ''))
#This thing does not look clean; it feels hacky
print(marks)

re.findall() 返回列表是這樣的

['>1\n', '>1\n', ...]

但我想要這樣的東西

['1', '1', ...]

我該怎么做?

我會在這里使用正則表達式查找所有方法:

string = """
Q1
|-->1
|-->1
|-->1
|-->1
|-->1
"""

grades = re.findall(r'-->(\d+)', string)
print(grades)  # ['1', '1', '1', '1', '1']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM