简体   繁体   English

如何在python中将每个单词的第一个字母大写而不使用.capitalize or.upper or.title

[英]how to capitalize first letter of every word without .capitalize or .upper or .title in python

I currently have:我目前有:

def myTitle(string):
    index = 0
    title = ''
    while index < len(string):
        if string[index] == ' ':
            upper=string[index+1]
            upper = (ord(upper) - 32)
            title = title + ' ' + chr(upper)
        else:
            title = title + string[index]

String is defined as "I like coffee a lot" but title gets returned as "I Llike Ccoffee Aa Llot"字符串被定义为“我非常喜欢咖啡”,但标题被返回为“我喜欢 Ccoffee Aa Llot”

You've just forgotten 3 lines: index+=1 twice and return title您刚刚忘记了 3 行: index+=1两次并return title

The fixed function looks like this:固定的 function 看起来像这样:

def myTitle(string):
    index = 0
    title = ''
    while index < len(string):
        if string[index] == ' ':
            upper=string[index+1]
            upper = (ord(upper) - 32)
            title = title + ' ' + chr(upper)
            index+=1
        else:
            title = title + string[index]
        index+=1
    return title

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM