如何在 Python 中替换字符串中的连字符和换行符



我正在处理具有多个音节划分的文本。

典型的字符串是这样的

"this good pe-
riod has"

我试过了:

my_string.replace('-'+"r","")

但是,它不起作用。

我想得到

"this good period has"

你试过这个吗?

import re
text = """this good pe-
riod has"""
print(re.sub(r"-s+", '', text))
# this good period has

匹配-后,应匹配换行符n

my_string = """this good pe-
riod has"""
print(my_string.replace("-n",""))
# this good period has

这取决于字符串的结尾方式,您也可以使用 re.sub 和-(?:r?n|r)使用my_string.replace('-rn', '')或可选的回车

符如果在前后必须有一个单词字符,而不是删除行尾的所有连字符,您可以使用 lookaround:

(?<=w)-r?n(?=w)

正则表达式演示 |蟒蛇演示

例如

import re
regex = r"(?<=w)-r?n(?=w)"
my_string = """this good pe-
riod has"""
print (re.sub(regex, "", my_string))

输出

this good period has