Python 如何替换代码,而不是将其他代码大写?
输出:Python 如何替换代码,而不是将其他代码大写?,python,for-loop,if-statement,str-replace,capitalize,Python,For Loop,If Statement,Str Replace,Capitalize,输出: Hello world helloh worldw helloh 但是,如果单词中的字母与我要大写的字母相同,那么单词中的字母也会大写 输入: sentence = str ( input ( "Enter a sentence:" ) ) sentence = sentence.split ( ) new = "" for word in sentence: wordi = ord ( word[ 0 ] ) cap =
Hello world
helloh worldw
helloh
但是,如果单词中的字母与我要大写的字母相同,那么单词中的字母也会大写
输入:
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 )
Hello World
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 )
输出:
Hello world
helloh worldw
helloh
我尝试在替换中切换“a”变量,并在if-else语句中的变量new中添加a到new
HelloH WorldW
输出:
Hello world
helloh worldw
helloh
如何使代码工作?您可以使用方法的
count
参数,仅替换一次
Hello
将所有内容放在一个方法中,以便于使用,然后
word1 = word.replace(word[0], a, 1)
def大写(句子):
if isinstance(句子,str):#句柄字符串,if尚未拆分
句子=句子。拆分()
new=“”
对于句子中的单词:
ow=ord(字[0])
如果97因为您不能使用str.upper()
方法,那么让我们自己定义一个upper()
函数:
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
当然,for循环可以被列表替换
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))
使用您的输入运行此命令会得到您期望的输出:
输入一句话:helloh worldw
嗨,世界
要大写所有前几个字符,这是效率最高的字符(按行)
这一个也可以,但是需要多行代码才能完成。就我个人而言,如果您是初学者,我建议您使用第二种方法,因为我也是初学者,所以更容易理解。无需担心,没有看到原始方法中的拆分!