![](/img/trans.png)
[英]How to get the last 3 characters of each word of a given string using short regex syntax?
[英]How I can get last word in the given string without using if condition for index?
Q. 編寫一個 python 函數 encrypt_sentence(msg) ,它接受一條消息並根據下面給出的規則對其進行加密並返回加密的消息。
奇數位置的單詞 -> 反轉
偶數位置的單詞 -> 重新排列字符,使所有輔音都出現在元音之前,並且它們的順序不應改變
注意:假設句子以一個單詞開頭,並且單詞之間只有一個空格。
必要時執行區分大小寫的字符串操作。
#Rearranging the characters so that all consonants appear before the vowels and their order should not change
def consonants_vowels(str):
vowels_string = "aAeEiIoOuU" # all Vowels in lowercase and uppercase
vowel = ""
consonants = ""
for i in range(0, len(str)):
if str[i] in vowels_string:
vowel = vowel + str[i] #adding vowels
else:
consonants += str[i] #adding consonants
return consonants + vowel + " " # " " to make space between words
str = "How to resolve"
count = 1
word = ""
final_string = ""
for i in range(0, len(str)):
if str[i] != " " and i + 1 != len(str): #getting each word from string
word += str[i]
else:
if count % 2 != 0: #to check word at odd postion
final_string += word[::-1] + " " #reversing string at odd position
else:
final_string = final_string + consonants_vowels(word)
count += 1
word = ""
print(final_string)
預期輸出: woH to evloser
代碼輸出: woH to vloser
這花了我一分鍾的時間,但是您問題的答案是一步一步調試的問題(一次一步地執行您的程序,直到發生您意想不到的事情/事情中斷)。
在這種情況下,問題出在您的最后一個字母循環上。 那是當你檢查i + 1 !- len(str)
你的問題是你只將字母str[i]
到word
IFF i != len(str)
但當然i+1 == len(str)
在循環的最后一次執行時,它永遠不會將e
添加到單詞中,因此,正如我們所期望的,當它反轉單詞(它正確地執行)時,也沒有e
肯定有幾種方法可以解決這個問題,但這是我的方法:
首先,我們確實希望在i = len(str)
時添加字母 - 在您的示例文本中,i = 13,因此我們將從該行中移除 +1。
接下來,我們需要再次運行循環之后 i = 13 循環(添加e
循環),以便我們可以檢查是否完成(即, if i >= len(str)
或者換句話說,我們檢查它是否不是 -- <
-- 然后下降到 else ,因為那 -- 14 < 14
現在是假的。所以我們將從前面取+1
並將其粘貼在循環將要執行的次數中執行 -- for i in range(0, len(str)+1):
所以這將是當 i = 14 (超出str
的索引)所以......
我們還需要交換and
的條件and
因為當i = 14
時str[i]
會拋出錯誤,因為在長度為 14 的字符串中沒有第 15 項(索引為 14)。
這是最終的工作代碼。 希望解釋能幫助您了解將來如何執行此操作。
#Rearranging the characters so that all consonants appear before the vowels and their order should not change
def consonants_vowels(str):
vowels_string = "aAeEiIoOuU" # all Vowels in lowercase and uppercase
vowel = ""
consonants = ""
for i in range(0, len(str)):
if str[i] in vowels_string:
vowel = vowel + str[i] #adding vowels
else:
consonants += str[i] #adding consonants
return consonants + vowel + " " # " " to make space between words
str = "How to resolve"
count = 1
word = ""
final_string = ""
for i in range(0, len(str)+1):
if i < len(str) and str[i] != " " : #getting each word from string
word += str[i]
else:
if count % 2 != 0: #to check word at odd postion
final_string += word[::-1] + " " #reversing string at odd position
else:
final_string = final_string + consonants_vowels(word)
count += 1
word = ""
print(final_string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.