在不使用任何外部/匯入函式的情況下,我無法找到如何使用Python交換字串中的兩個單詞。
我擁有的是從文本檔案中獲取的字串。例如字串是:
line = "歡迎來到您的個人儀表板,您可以在其中找到 GitHub 作業原理的介紹、幫助您構建軟體的工具以及幫助合并您的第一行代碼。"
我從串列中找到最長和最短的單詞,其中包含行字串中的所有單詞,沒有標點符號。
最長=“介紹”
最短=“到”
我需要做的是將最長和最短的單詞交換在一起,同時保持標點符號完整。
嘗試使用替換,但只能用另一個替換 1 個單詞,但第二個單詞保持不變。
不知道究竟要使用什么或如何使用。
該字串的結尾必須是:“歡迎來到您的個人儀表板,您可以在其中找到GitHub 作業原理的介紹、幫助您構建軟體的工具以及幫助合并您的第一行代碼。”
交換時:“歡迎來到您的個人儀表板,您可以在其中找到GitHub作業原理、工具介紹幫助您構建軟體,并幫助合并您的第一行代碼。”
嘗試將其替換為:newline = newline.replace(shortest, longest)
但如前所述,它只會替換 1 個單詞。
uj5u.com熱心網友回復:
您將需要將文本拆分為每個單詞,并根據大小找到最小/最大單詞。之后,遍歷拆分詞并檢查它是否等于最小/最大詞。如果是,那么您需要用正確的詞替換它。
import string #to check for punctuation
line = "Welcome to your personal dashboard, where you can find an introduction to how GitHub works, tools to help you build software, and help merging your first lines of code."
words = line.split() #this includes punctuation attached to words as well
shortest = min(words, key = len) #find the length of the words that is the smallest
longest = max(words, key = len) #opposite of above
for i, word in enumerate(words): #iterate with both the index and word in the list
if word == shortest:
if word[-1] in string.punctuation: #check if the punctuation is at the end since we want to keep it
words[i] = longest word[-1] #this keeps the punctuation
else:
words[i] = longest
elif word == longest:
if word[-1] in string.punctuation:
words[i] = shortest word[-1]
else:
words[i] = shortest
line = ' '.join(words) #make a new line that has the replaced words
uj5u.com熱心網友回復:
如果這是家庭作業或作業(因為性能無關緊要),那么我對您的建議是將單詞 1 替換為{word1},單詞 2替換為{word2},然后執行字串格式。解決方案變為:
line = line.replace(longest, "{word1}").replace(shorted, "{word2}")
line = line.format(word1=shortest,word2=longest)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535259.html
標籤:Python细绳代替交换
上一篇:從字串中洗掉小數
下一篇:在字串中查找數字并按它們排序
