转换字符串,删除特殊字符并替换

时间:2016-11-10 16:11:54

标签: python string python-2.7

我需要转换我的字符串,以便将其制作成特殊格式

例如:

string = "the cow's milk is a-okay!"

converted string = "the-cows-milk-is-a-okay"

4 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

这个怎么样(缺点是无法保持连字符-),

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

答案 2 :(得分:0)

>>> 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'

答案 3 :(得分:0)

可以使用简单的生成器表达式来实现此目的:

>>> 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'
>>>