我正在撰寫一個程式,該程式從用戶那里獲取陳述句或短語并將其轉換為首字母縮略詞。
它應該看起來像:
Enter statement here:
> Thank god it's Friday
Acronym : TGIF
我發現完成此操作的最佳方法是通過串列并使用.split()將每個單詞分成自己的字串,并且能夠隔離第一項的第一個字母,但是當我嘗試通過更改來修改以下專案的程式時將宣告列印到:
print("首字母縮略詞:", x[0:][0])
它只是最終列印第一項中的全部字母。
這是我到目前為止所得到的,但是它只列印第一個專案的第一個字母......
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
print("Acronym :", x[0][0])
uj5u.com熱心網友回復:
使用re.sub回呼我們可以嘗試:
inp = "Peas porridge hot"
output = re.sub(r'(\S)\S*', lambda m: m.group(1).upper(), inp)
print(output) # PPH
uj5u.com熱心網友回復:
acroPhrase = str(input("Enter a sentence or phrase : "))
acroPhrase = acroPhrase.upper()
x = acroPhrase.split(" ")
result = ''
for i in x:
word = list(i)
result =word[0]
print(result)
uj5u.com熱心網友回復:
代碼需要遍歷.split結果。例如,使用串列推導:
inp = "Thank god its friday"
inp = inp.split()
first_lets = [word[0] for word in inp]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/454235.html
