如果字串中沒有一個特殊字符,我會嘗試在特殊字符后添加一個空格。
這是我的代碼
import re
line='Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
for i in re.finditer(r"\?|!|\.", line):
if line[i.end()]!=' ':
line=line.replace(line[i.end()],line[i.end()] ' ')
預期輸出:
"Hello there! This is Robert. Happy New Year! Are you surprised? Im not."
我的代碼的輸出:
"Hello t here! This is Robert . Happy New Year!A re you surprised? Im not ."
我仍然沒有弄清楚為什么它不起作用。
uj5u.com熱心網友回復:
利用
re.sub(r'([!?.])(?=\S)', r'\1 ', line)
請參閱正則運算式證明。
解釋
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[!?.] any character of: '!', '?', '.'
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
(?= look ahead to see if there is:
--------------------------------------------------------------------------------
\S non-whitespace (all but \n, \r, \t, \f,
and " ")
--------------------------------------------------------------------------------
) end of look-ahead
蟒蛇代碼:
import re
line='Hello there! This is Robert. Happy New Year!Are you surprised?Im not.'
line = re.sub(r'([!?.])(?=\S)', r'\1 ', line)
結果:Hello there! This is Robert. Happy New Year! Are you surprised? Im not.
uj5u.com熱心網友回復:
您可以將以下正則運算式與re.sub, 使用(零寬度)匹配替換為一個空格:
(?<=[!?.])(?=\S)
(?<=[!?.])是一個否定的lookbehind,它斷言字串位置在給定字符類中的三個字符之一之前,并(?=\S)斷言當前字串位置后跟一個不是空格的字符。
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401841.html
上一篇:將分鐘轉換為整小時,無需天
下一篇:這個回圈可以在串列理解中完成嗎?
