python - 关于 Python 首词

标签 python string capitalize

from string import capwords

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

为什么不等于这个? ↓

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

我该怎么做?

最佳答案

documentation对于 string.capwords() 说:

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

如果我们一步一步来:

>>> 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" 没有大写。

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

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

关于python - 关于 Python 首词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44094703/

相关文章:

python - 我在任何地方都找不到我的错误

python - PySpark - 显示数据框中列数据类型的计数

python - 避免在 multiprocessing.Pool worker 中使用全局变量来获取不可篡改的共享状态

c++ - 接受第一个字符串输入然后忽略其余的

c++ - stringstream str 函数有什么问题?

vb.net - 如何只在句首大写字母,下一个单词正常

javascript - 在 Selenium 中获取 Javascript 代码的返回值

C字符串连接

regex - 使用 Vim 将所选内容中每个单词的首字母大写

css - 如何使用 CSS 大写第一行?::first-line 伪元素不起作用