我需要我的字符串轉換,使其製作成特殊格式轉換爲字符串,刪除特殊字符和更換
例如:
string = "the cow's milk is a-okay!"
converted string = "the-cows-milk-is-a-okay"
我需要我的字符串轉換,使其製作成特殊格式轉換爲字符串,刪除特殊字符和更換
例如:
string = "the cow's milk is a-okay!"
converted string = "the-cows-milk-is-a-okay"
import re
s = "the cow's milk is a-okay!"
s = re.sub(r'[^a-zA-Z\s-]+', '', s) # remove anything that isn't a letter, space, or hyphen
s = re.sub(r'\s+', '-', s) # replace all spaces with hyphens
print(s) # the-cows-milk-is-a-okay
這裏一個「空間」是任何包含製表符和換行符的空白字符。要更改此設置,請將\s
替換爲實際空格字符。
多個空格的運行將被替換爲一個連字符。要更改此設置,請在第二次撥打re.sub
時刪除+
。
中的「 - 」再次加入字符串'\ W +'會更好嗎? –
@ cricket_007不,這不適用於空格,連字符或下劃線。 –
@AlexHall非常感謝!我真的必須重新研究這個。 –
這個怎麼樣(缺點是無法維持的連字符-
),
import string
s = "the cow's milk is a-okay!"
table = string.maketrans(" ", "-")
new_s = s.translate(table, string.punctuation)
print(new_s)
# the-cows-milk-is-aokay
這不是OP想要的。具有諷刺意味的是,你承認在你的答案。 –
>>> string = "the cow's milk is a-okay!"
>>> string
"the cow's milk is a-okay!"
>>> string = string.replace(' ','-')
>>> for char in string:
... if char in "?.!:;/'":
... string = string.replace(char,'')
...
>>> string
'the-cows-milk-is-a-okay'
一個簡單的生成器表達式可以用來實現這一點:
>>> s = "the cow's milk is a-okay!"
>>> ''.join(('-' if el == " " else el if el not in "?.!:;/'" else "" for el in s))
'the-cows-milk-is-a-okay'
>>>
聽起來不錯。試過什麼了嗎? –
這可能是''''join(s.split())',但符號移除要求會使其變得模糊 –
看看[String slugification in Python](http://stackoverflow.com/questions/5574042/string- slugification-in-python) –