我有一個字串:
string = "Hello World"
這需要更改為:
"hello WORLD"
在 Python 中僅使用 split 和 join。
有什么幫助嗎?
string = "Hello World"
split_str = string.split()
然后無法弄清楚如何將第一個單詞轉換為小寫第二個單詞轉換為大寫并加入
uj5u.com熱心網友回復:
僅使用split()和join()無法實作OP 的目標。這些函式都不能用于轉換為大寫或小寫。
itertools模塊中的回圈類非常適合:
from itertools import cycle
words = 'hello world'
CYCLE = cycle((str.lower, str.upper))
print(*(next(CYCLE)(word) for word in words.split()))
輸出:
hello WORLD
uj5u.com熱心網友回復:
下面的代碼適用于任意數量的單詞:
string = "Hello World"
words = string.split() # works also for multiple spaces and tabs
result = ' '.join((w.upper() if i&1 else w.lower()) for i,w in enumerate(words))
print(result)
# "hello WORLD"
uj5u.com熱心網友回復:
很多話:
使用split
" "使用連接一切join
在里面我們使用i最多這個串列的長度來遍歷串列
如果這是一個奇數,則upper否則lower(因為串列從 0 開始編號,我們需要每隔一個)
string = "Hello World! It is Sparta!"
split_str = string.split()
print(" ".join(split_str[i].upper() if i&1 else split_str[i].lower() for i in range(len(split_str))))
# hello WORLD! it IS sparta!
兩個詞(簡單的解決方案):
string = "Hello World"
split_str = string.split()
print(' '.join([split_str[0].lower(),split_str[1].upper()]))
# hello WORLD
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/532077.html
下一篇:選擇至少沒有一個子元素的記錄
