Python单词首字母大写代码失效问题:已用upper()但无效果
问题:句子单词首字母大写程序无效果
我想写个程序,接收句子输入,把每个单词的首字母转成大写,代码如下:
input_sentence = input("Enter a sentence: ") words = input_sentence.split() for word in words: edited_word = word[0].upper() + word[1:] print("Edited sentence:", ' '.join(words))
运行后句子完全没变化,输入测试语句:
Enter a sentence: i am writing a sentence Edited sentence: i am writing a sentence
期望输出是:
Enter a sentence: i am writing a sentence Edited sentence: I Am Writing A Sentence
问题原因
你确实用了upper()生成了首字母大写的edited_word,但根本没把这个修改后的单词存回原列表words里。循环里只是生成了临时变量,原列表的元素从头到尾没被改动,最后join的还是最初的words,所以输出和输入一样。
修正方案
有两种简单的修改方式:
方式1:用列表推导式直接生成修改后的列表
input_sentence = input("Enter a sentence: ") words = input_sentence.split() # 直接生成首字母大写的新列表 capitalized_words = [word[0].upper() + word[1:] for word in words] print("Edited sentence:", ' '.join(capitalized_words))
方式2:循环时修改原列表的元素
input_sentence = input("Enter a sentence: ") words = input_sentence.split() # 通过索引修改原列表的元素 for i in range(len(words)): words[i] = words[i][0].upper() + words[i][1:] print("Edited sentence:", ' '.join(words))
补充:更简洁的方法
Python字符串有内置的capitalize()方法,专门用来把单词首字母大写、其余字母小写,用它可以简化代码:
input_sentence = input("Enter a sentence: ") capitalized_words = [word.capitalize() for word in input_sentence.split()] print("Edited sentence:", ' '.join(capitalized_words))
内容的提问来源于stack exchange,提问作者Leon
相关产品推荐
相关产品推荐

