【Python】首字母大写 capitalize()

一、题目

You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.

alison heck ==> Alison Heck

Given a full name, your task is to capitalize the name appropriately.

Sample Input 1

chris alan

Sample Output 1

Chris Alan

 

Sample Input 2

1 w 2 r 3g

Sample Output 2

1 W 2 R 3g

二、代码

 

#!/bin/python3

import math
import os
import random
import re
import sys

def solve(s):
    str = s.split(' ')
    result = ''

    for i in range(len(str)):
        str[i] = str[i].capitalize() if not str[i].isdigit() else str[i]

    result = ' '.join(str)
    return result

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    s = input()
    result = solve(s)
    
    fptr.write(result + '\n')
    fptr.close()

三、解读

str = s.split(' ')

在 solve 函数内部,使用 split() 方法将字符串 s 按空格分割成单词,并存储在列表 str 中。   

for i in range(len(str)):
    str[i] = str[i].capitalize() if not str[i].isdigit() else str[i]

循环遍历每个元素,使用 capitalize() 方法,将字符串首字母大写,其余字母小写。

如果元素是一个数字(使用 isdigit() 方法检查),则保持不变。

result = ' '.join(str)

使用 join() 方法将列表 str 中的元素(现在是经过处理的单词)用空格连接起来,形成最终的字符串 result。

fptr = open(os.environ['OUTPUT_PATH'], 'w')

打开一个文件,其路径由环境变量 OUTPUT_PATH 指定,以写入模式打开。文件对象存储在变量 fptr 中。

fptr.write(result + '\n')

使用 write() 方法将 result 写入到文件中,然后在末尾添加一个换行符。

fptr.close()

关闭文件对象 fptr,确保所有内容都已正确写入并保存。

  • 4
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值