Python程序将文件中每个单词的第一个字母大写
以下文章包含读取文件并将文件中每个单词的第一个字母大写并将其打印为输出的程序。为了将第一个字母大写,我们将使用Python中的title()函数。 Python中的title函数是Python String Method,用于将字符串中每个单词的第一个字符转为大写,其余字符转为小写,并返回新的字符串。
例子:
# Content of the file serves as input
Input: hello world
Output: Hello World
# Content of the file serves as input
Input: geeks for geeks
Output: Geeks For Geeks
方法:
- 我们将文件的内容作为输入。
- 我们将使用Python中的open()函数打开文件并保存其内容。
- 修改后打印内容。
输入文件:
下面是实现。
Python3
# Python program to read a file and capitalize
# the first letter of every word in the file.
# A file named "gfg", will be opened with the
# reading mode.
file_gfg = open('gfg.txt', 'r')
# This will traverse through every line one by one
# in the file
for line in file_gfg:
# This will convert the content
# of that line with capitalized
# first letter of every word
output = line.title()
# This will print the output
print(output)
输出:
Geeksforgeeks Is A Computer Science Portal For Geeks. It Contains Well Written, Well Thought And Well Explained Computer Science And Programming Articles, Quizzes Etc.