📜  Python字符串| capwords() 方法

📅  最后修改于: 2022-05-13 01:55:47.989000             🧑  作者: Mango

Python字符串| capwords() 方法

在Python中,字符串capwords()方法用于使用 split() 方法将字符串中的所有单词大写。

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

Python3
# imports string module
import string
 
sentence = 'Python is one of the best programming languages.'
 
# sep parameter is left None
formatted = string.capwords(sentence, sep = None)
 
print(formatted)


Python3
# imports string module
import string
 
sentence = 'Python is one of the best programming languages.'
 
# sep parameter is 'g'
formatted = string.capwords(sentence, sep = 'g')
print('When sep = "g"', formatted)
 
# sep parameter is 'o'
formatted = string.capwords(sentence, sep = 'o')
print('When sep = "o"', formatted)


输出:
Python Is One Of The Best Programming Languages.


代码 #2:sep不是None 时。

Python3

# imports string module
import string
 
sentence = 'Python is one of the best programming languages.'
 
# sep parameter is 'g'
formatted = string.capwords(sentence, sep = 'g')
print('When sep = "g"', formatted)
 
# sep parameter is 'o'
formatted = string.capwords(sentence, sep = 'o')
print('When sep = "o"', formatted)
输出:
When sep = "g" Python is one of the best progRamming langUagEs.
When sep = "o" PythoN is oNe oF the best proGramming languages.