3 回答

TA貢獻1812條經驗 獲得超5個贊
使用與您想要小寫的模式匹配的正則表達式。
import re
def maybe_downcase(s):
if re.match(r'^[A-Z_-]+(?:\s\(.*\))?$', s):
return s.lower()
else:
return s
output = [maybe_downcase(x) for x in L1]
正則表達式匹配一系列大寫字母、下劃線和連字符,可選地后跟空格和括號中的任何內容。

TA貢獻1806條經驗 獲得超5個贊
您可以執行您在問題中提到的類似方法,但檢查字符串中出現的任何小寫字母,而不是匹配大寫字母(沒有導入):
[x if any(y.islower() for y in x.split('(')[0]) else x.lower() for x in L1]
輸出:
['threshold_band',
'threshold_band (copy)',
'ticker',
'ticker-two',
'Title C (copy)',
'Title C (copy) (copy)']

TA貢獻1794條經驗 獲得超7個贊
這會給你正確的輸出嗎?
L1 = ['THRESHOLD_BAND', 'THRESHOLD_BAND (copy)', 'TICKER', 'TICKER-TWO',
'Title C (copy)', 'Title C (copy) (copy)']
L2 = []
for strng in L1:
s0, *s1 = strng.split('(', 1)
s0 = s0.lower() if s0 == s0.upper() else s0
L2.append('('.join((s0, *s1)))
print(*L2, sep='\n')
輸出:
threshold_band
threshold_band (copy)
ticker
ticker-two
Title C (copy)
Title C (copy) (copy)
添加回答
舉報