這是我第一次學習python。我在本科期間(多年前)上過兩節 C 編程課程。我通常了解基本演算法,但很難寫出代碼。
目前在做UDEMY的課程,問題要求我們將字串的第一個和第三個字母大寫。我已經撰寫了代碼(花了我一段時間)并且它可以作業,但我知道它并不漂亮。
請注意:嘗試在不使用 enumerate 函式的情況下對其進行編碼。
def wordplay(text):
first = text[0:1] #isolate the first letter
third = text[2:3] #isolate the third letter
firstc = first.capitalize() #capitalize the first letter
thirdc = third.capitalize() #capitalize the third letter
changedword = firstc text[1:2] thirdc text[3:] #change the first and third letter to capital in the string
print(changedword)
該代碼有效,但希望改進我的邏輯(不使用列舉)
uj5u.com熱心網友回復:
這是使用該capitalize()功能的一個選項:
inp = "hello"
output = inp[0:2].capitalize() inp[2:].capitalize()
print(output) # HeLlo
這里的想法是將兩個子字串大寫,一個用于前兩個字母,另一個用于字串的其余部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/452146.html
標籤:python-3.x 细绳 功能 大写
