简体   繁体   English

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

[英]Converting a string, removing special characters and replacing

I need to convert my string so that it is made into a special format 我需要将我的字符串转换为特殊格式

ex: 例如:

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

Here a 'space' is any whitespace character including tabs and newlines. 这里的“空格”是任何空格字符,包括制表符和换行符。 To change this, replace \\s with the actual space character 要更改此设置,请用实际的空格字符替换\\s .

Runs of multiple spaces will be replaced by a single hyphen. 多个空格的运行将被单个连字符代替。 To change this, remove the + in the second call to re.sub . 要更改此设置,请在第二个re.sub调用中删除+

How about this (the drawback is unable to remain the hyphen - ), 怎么样(缺点是不能保留连字符- ),

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

A simple generator expression could be used to accomplish this: 一个简单的生成器表达式可以用来完成此任务:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM