【问题标题】:About Python capwords关于 Python 大写字母
【发布时间】:2017-10-21 00:56:33
【问题描述】:
from string import capwords

capwords('\"this is test\", please tell me.')
# output: '\"this Is Test\", Please Tell Me.'
             ^

为什么不等于这个? ↓

'\"This Is Test\", Please Tell Me.'
   ^

我该怎么做?

【问题讨论】:

  • string 模块是 Python 1 的遗留物,在 Python 2.0 引入字符串方法时几乎完全过时。你几乎从不需要import string。我只能想到两个例外:maketrans()(我不时使用)和依赖于语言环境的大写/小写内容(我从未使用过)。
  • 谢谢大家。使用.title() 解决了这个问题。
  • string 模块没有什么过时的。一些函数在 Python 2 中被弃用,取而代之的是 str 上的方法。这些在 Python 3 中消失了,因此使用 string 模块与这些无关。请参阅文档:docs.python.org/3/library/string.html

标签: python string capitalize


【解决方案1】:

documentation 代表 string.capwords() 说:

使用str.split() 将参数拆分为单词,使用str.capitalize() 将每个单词大写,使用str.join() 连接大写单词。如果可选的第二个参数 sep 不存在或 None,则空白字符的运行将替换为单个空格并删除前导和尾随空格,否则 sep 用于拆分和连接单词。

如果我们一步一步来:

>>> s = '\"this is test\", please tell me.'
>>> split = s.split()
>>> split
['"this', 'is', 'test",', 'please', 'tell', 'me.']
>>> ' '.join(x.capitalize() for x in split)
'"this Is Test", Please Tell Me.'

因此您可以看到双引号被视为单词的一部分,因此以下"t"s 没有大写。

应该使用字符串的str.title() 方法:

>>> s.title()
'"This Is Test", Please Tell Me.'

【讨论】:

  • 我正要发布同样的东西:-D
【解决方案2】:

它不起作用,因为它很幼稚并且被领先的" 混淆,这使它认为"This 不是以字母开头。

改用内置的字符串方法.title()

>>> '\"this is test\", please tell me.'.title()
'"This Is Test", Please Tell Me.'

这可能是capwords() 保留在string 模块中但从未成为字符串方法的原因。

【讨论】:

  • 从 2.x 开始,string.capwords 一直是内置函数。很少使用。
  • 有用,但在你不想大写的地方会失败,例如123abc -> 123Abc。
  • 大写是关于文本,而不是关于任意字符串。要与这些人一起工作,您需要编写一个功能来满足您的需求。
猜你喜欢
  • 2013-06-25
  • 1970-01-01
  • 2019-08-08
  • 1970-01-01
  • 2012-09-06
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 2015-10-24
相关资源
最近更新 更多