Python字符串| capwords() 方法
在Python中,字符串capwords()方法用于使用 split() 方法将字符串中的所有单词大写。
Syntax: string.capwords(string, sep=None)
Return Value: Returns a formatted string after above operations.
使用 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.