gpt4 book ai didi

python - 如何将可能包含数字的字符串中的首字母大写

转载 作者:太空狗 更新时间:2023-10-29 20:13:21 27 4
gpt4 key购买 nike

我想通读一个文件并使用 Python 将字符串中的第一个字母大写,但有些字符串可能首先包含数字。具体来说,该文件可能如下所示:

"hello world"
"11hello world"
"66645world hello"

我希望它是:

"Hello world"
"11Hello world"
"66645World hello"

我尝试了以下方法,但这仅在字母位于第一个位置时才大写。

with open('input.txt') as input, open("output.txt", "a") as output:
for line in input:
output.write(line[0:1].upper()+line[1:-1].lower()+"\n")

有什么建议吗? :-)

最佳答案

使用正则表达式:

for line in output:
m = re.search('[a-zA-Z]', line);
if m is not None:
index = m.start()
output.write(line[0:index] + line[index].upper() + line[index + 1:])

关于python - 如何将可能包含数字的字符串中的首字母大写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53099204/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com