我需要從以數字或特殊字符開頭的字串中洗掉單詞。我不能簡單地輸入特定值,因為字串是基于用戶輸入的,所以它是未知的。所有我能夠想出的,而無需匯入任何東西,就是使用
.startswith(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, '!', '"', '#', '$', '%', '&', '(', ')', '*', ' ', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\', ']', '^', '_', '`', '{', '|', '}', '~', ')', ':')
一定有一種更簡單、更短的方法,對吧?
uj5u.com熱心網友回復:
我需要從以數字或特殊字符開頭的字串中洗掉單詞。[...]
我建議看一下string模塊。這是一個內置模塊,用于定義常見字符,例如標點符號、數字、字母數字字符等。
從那里,將所需的變數從string模塊傳輸為您在代碼中定義的變數應該足夠簡單了:
digits = '0123456789'
punctuation = r"""!"#$%&'()* ,-./:;<=>?@[\]^_`{|}~"""
invalid_start_chars = digits punctuation
然后使用示例輸入進行測驗:
string = "Hello 123World H0w's @It [Going? Testing123"
print(' '.join(
[word for word in string.split()
if word[0] not in invalid_start_chars]
))
輸出:
Hello H0w's Testing123
uj5u.com熱心網友回復:
我建議使用標準模塊string。
from string import punctuation
def check_word(word: str) -> bool:
return not word.startswith(tuple(punctuation '0123456789'))
def fix_string(s: str) -> str:
return " ".join(word for word in s.split() if check_word(word))
所以你可以使用這樣的函式fix_string:
s = "Hello !world! This is a good .test"
print('Result:', fix_string(s))
# Result: Hello This is a good
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/362730.html
下一篇:如何在Rust中加入字符向量
