我使用 re.sub
在每个大写字母后添加空格
>>> re.sub(r"(\w)([A-Z])", r"\1 \2", "WordWordWord")
'Word Word Word'
但我不知道如何解决以下问题
我有这样的字符串 ' 90.5% Voted Creative 90.5% Voted Uplifted 91.5% Voted Energetic'
并且我想在开始字符串中的每个数字之前添加逗号,除了第一个数字。所以结果将是这样的:
' 90.5% Voted Creative ,90.5% Voted Uplifted ,91.5% Voted Energetic'
我试过了:
>>> finallist = [ ", ".join(item.split(" ")) for item in mylist ]
>>> finallist
[', 90.5%, VotedCreative, 90.5%, VotedUplifted, 91.5%, VotedEnergetic']
它在我不想要的每个字符串后添加逗号
如何在 python 中使用 re.sub
或任何更好的方法来做到这一点???
答案 0 :(得分:2)
re.sub(r'(?<=\S)(?=\s\d)', ',', s)
与 wjandrea 的答案相同的想法,但适用于 Python 3.6。 re.split('(?<=\S)(?=\s\d)', s)
不适用于 Python 3.6(至少不适用于 Python 3.6.7):ValueError: split() requires a non-empty pattern match.
使用起来效果更好
re.sub(r'(?<=[^\s,])(?=\s+\d)', ',', s)
[^,\s]
:如果已经有一个 ',' 就不会插入 ','([^\s]
等价于 \S
)
\s+
:如果有多个空格,请在正确的位置插入“,”。
答案 1 :(得分:1)
您可以将 re.split()
与环视结合使用:
>>> s = ' 90.5% Voted Creative 90.5% Voted Uplifted 91.5% Voted Energetic'
>>> ','.join(re.split('(?<=\S)(?=\s\d)', s))
' 90.5% Voted Creative, 90.5% Voted Uplifted, 91.5% Voted Energetic'
说明:
(?<=...)
- Lookbehind
\S
- 非空白字符(?=...)
- Lookahead
\s
- 空白字符\d
- 数字答案 2 :(得分:1)
这是我的简单方法。为避免出现第一个逗号,您可以使用 str.strip()
删除前导空格。
text = ' 90.5% Voted Creative 90.5% Voted Uplifted 91.5% Voted Energetic'
print(re.sub(r" ([0-9.]+)", r", \1", text.strip()))
输出:
'90.5% Voted Creative, 90.5% Voted Uplifted, 91.5% Voted Energetic'
答案 3 :(得分:0)
您还可以将 re.sub
与 count
参数一起使用:
s = " 90.5% Voted Creative 90.5% Voted Uplifted 91.5% Voted Energetic"
import re
regexp = r'(\d+\.\d+\%)'
result = re.sub(regexp, r',\1', s)
result = re.sub(',' + regexp, r'\1', result, 1)
print(result)