温馨提示×

python如何把单词首字母大写

小亿
98
2023-12-11 20:23:35
栏目: 编程语言

在Python中,可以使用字符串的capitalize()方法来将单词的首字母大写。该方法会返回一个新的字符串,其中第一个字符将会被转换为大写,而其他字符将会被转换为小写。下面是一个示例:

word = "hello"
new_word = word.capitalize()
print(new_word)  # 输出 "Hello"

如果你想将整个字符串中的每个单词的首字母都大写,可以使用字符串的title()方法。该方法会返回一个新的字符串,其中每个单词的首字母都会被转换为大写。下面是一个示例:

sentence = "hello world"
new_sentence = sentence.title()
print(new_sentence)  # 输出 "Hello World"

0