如何不通过大写其他代码来替换代码?

How to replace a code not by capitalizing the other ones?

sentence = str ( input ( "Enter a sentence:" ) )
sentence = sentence.split ( )

new = ""
for word in sentence:
    wordi = ord ( word[ 0 ] )
    cap = word[ 0 ]
    a = chr ( (ord ( cap ) - 32) )
    word1 = word.replace ( word[ 0 ] ,a )

    if wordi <= 122 and wordi >= 97:
        new = new + word1 + " "
    else:
        new = new + word + " "

print ( new )

我一直在写一个代码,可以在不使用 capitalize 或 upper 函数的情况下将句子中的所有第一个字母大写。当单词中的字母与我要大写的字母不一样时,我写的代码似乎没问题。

输入:

Hello world

输出:

Hello World

但是,如果单词中的字母也和我要大写的字母一样,那么单词中的字母也会变成大写。

输入:

helloh worldw

输出:

HelloH WorldW

我尝试在替换中切换“a”变量,并在 if-else 语句的变量 new 中也添加 a 到 new。

sentence = str ( input ( "Enter a sentence:" ) )
sentence = sentence.split ( )

new = ""
for word in sentence:
    wordi = ord ( word[ 0 ] )
    cap = word[ 0 ]
    a = chr ( (ord ( cap ) - 32) )
    word1 = word.replace ( word[ 0 ] ,"" )

    if wordi <= 122 and wordi >= 97:
        new = new + a + word1 + " "
    else:
        new = new + word + " "

print ( new )

但是,代码竟然是单词中重复的字母在打印时会被删除。

输入:

helloh 

输出:

Hello

我怎样才能使代码工作?

可以使用str.replace方法的count参数,只替换一次

word1 = word.replace(word[0], a, 1)

全部放在一个方法中,方便使用,就得到了

def capitalize(sentence):
    if isinstance(sentence, str):    # handle string, if wasn't splitted already
        sentence = sentence.split()
    new = ""
    for word in sentence:
        ow = ord(word[0])
        if 97 <= ow <= 122:
            new += word.replace(word[0], chr(ow - 32), 1) + " "
        else:
            new += word + " "
    return new


print(capitalize(["Hello", "worldw"]))  # Hello Worldw
print(capitalize("Hello worldw"))       # Hello Worldw

既然不能使用str.upper()方法,那我们自己定义一个upper()函数:

def upper(char):
    # If more than one characters are given, capitalize all of them 
    if len(char) > 1:
        return ''.join(upper(c) for c in char)
    
    # if given character is between lowercase a and z, shift it to uppercase
    if "a" <= char <= "z":
        return chr(ord(char) - 32)
    else: # if not, return it unchanged
        return char

您只想用大写字母替换第一个字符。不幸的是,字符串是不可变的,所以你不能简单地做 word[0] = word[0].upper()

但是,您可以通过从其余字符中切出第一个字符来重建字符串,如下所示:word = word[0].upper() + word[1:].

或者,使用我们的 upper() 函数:word = upper(word[0]) + word[1:].

用您的代码实现:

sentence = str ( input ( "Enter a sentence:" ) )
sentence = sentence.split ( )

newsentence = []
for word in sentence:
    newword = upper(word[0]) + word[1:]
    newsentence.append(newword)

print(' '.join(newsentence))

当然,for循环可以用列表推导代替,

sentence = str ( input ( "Enter a sentence:" ) )
sentence = sentence.split ( )

newsentence = [upper(word[0]) + word[1:] for word in sentence]
print(' '.join(newsentence))

# Or you could pass the generator expression to the `str.join()` call
# To do this, replace the previous two lines with:
# print(' '.join(word[0].upper() + word[1:] for word in sentence))

运行 这与您的输入 helloh worldw 给出了您期望的输出:

Enter a sentence:helloh worldw
Helloh Worldw
def capitalize(lower_case_word):
    return ' '.join(x[:1].upper() + x[1:] for x in lower_case_word.split())

print(capitalize('hello I am nobody'))

首字母全部大写,这是效率最高的(按行)。

def capitalize(lower_case_word):
    lower_case_word = lower_case_word.split()
    new_phrase = ""

    for character in lower_case_word:
        new_phrase += character[0].upper() + character[1:] + ' '

    return new_phrase

print(capitalize('hello I am nobody'))

这个也可以,但是要多写几行代码才能完成。个人比较推荐第二种方法,初学者比较容易理解,我也是初学者