【问题标题】:How to capitalize sentences when middle of the sentence is enclosed in parenthesis like (unix)?当句子中间用括号括起来(如(unix))时,如何将句子大写?
【发布时间】:2020-12-24 20:28:18
【问题描述】:

假设我有像 S="python (unix)" 这样的字符串,我想得到以下输出:Python (Unix)。请给我建议。

在Python中读取文本文件时如何解决上述问题?

【问题讨论】:

  • 规则是每个单词的首字母大写吗?
  • 我们可以在python中使用title()或者capitalize()。
  • >>> s="python (unix)" >>> s.capitalize() 'Python (unix)'
  • 在上面的代码中,只有 P 变成了大写字母。我需要将第一个字母 U 也用 unix word 的大写字母制作。

标签: python file capitalize


【解决方案1】:

这是一种方法,使用 re.sub 和一个回调函数,该函数将每个匹配的单词大写:

S = "python (unix)"
out = re.sub(r'\b\w+\b', lambda m: m.group().capitalize(), S)
print(out)

打印出来:

Python (Unix)

【讨论】:

  • 当我们从文本文件中读取数据包含这种类型的场景时,如何做同样的例子?
  • 您应该为此提出一个新问题。 Stack Overflow 不是一个论坛,在您的原始问题得到回答后,讨论会继续进行。
猜你喜欢
  • 1970-01-01
  • 2015-09-25
  • 2022-11-16
  • 2017-01-01
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 2016-12-04
相关资源
最近更新 更多