Regex substitution in Python to add period to sentence that doesn't have one but only if it is the only line in string

huangapple go评论68阅读模式
英文:

Regex substitution in Python to add period to sentence that doesn't have one but only if it is the only line in string

问题

我想在字符串中的单个句子中添加句号,但字符串中没有句号,比如

string = "This is a sentence"

但要避免在像这样的内容中添加句号

string = "Item 1\nItem 2\nItem 3"

所以,如果字符串中的句子是唯一的一行,有办法添加句号吗?谢谢。

英文:

I'm looking to add periods to a single sentence in a string that doesn't have one, such as

string = "This is a sentence"

But while avoiding adding periods to things like

string = "Item 1\nItem 2\nItem 3"

So is there a way to add periods to a sentence if it is the only line in a string? Thanks.

答案1

得分: 0

你可以不使用正则表达式来实现。看看这些条件是否足够适用于你的情况:

s = "Some string"
s += "." if s[0].isupper() and not s.endswith(".") and "\n" not in s else ""
英文:

Actually you can do it without regex. Take a look if these conditions are enough in your case:

s = "Some string"
s += "." if s[0].isupper() and not s.endswith(".") and "\n" not in s else ""

huangapple
  • 本文由 发表于 2023年3月10日 01:04:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687796.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定