2016-03-04 244 views
-3

我在Python中有这样的字符串。在Python中删除字符串中的特殊字符

如何删除Python中的↑。

我已经尝试了谷歌提出的大多数方法,但似乎没有工作。

Lorem Ipsum 
        ↑ 



     The results really show what a poisonous 
+0

你可以发布你的代码,你试过了吗? – Hackaholic

+0

你是否明确表示只有箭头字符或任何特殊字符?标题和正文之间有冲突。 – dinos66

回答

3

你试过str.replace()

>>> s = '''Lorem Ipsum 
        ↑ 



     The results really show what a poisonous''' 
>>> s = s.replace('↑', '') 
>>> print(s) 
Lorem Ipsum 




     The results really show what a poisonous 

这在解释器中起作用。

# -*- coding: utf-8 -*- 
+0

非常感谢。我认为对我来说缺少的一点就是指定编码类型。 – CKCK

-1

我使用这个脚本在python替换和删除字符:

#!/usr/bin/env python 
# -*- coding: UTF-8 -*- 
#Script for replacing characters on plain text file 

original = open('input.txt', 'r') 
final = open('output.txt',"w") 

diccionario = [ 
("perros", "gatos"), 
("↑", "") 
] 

data = original.read() 
original.close() 
salida = reduce(lambda a, kv: a.replace(*kv), diccionario, data) 
final.write(salida) 
final.close() 
如果你的代码是在一个文件中,那么你可以通过将该线在顶部声明你的.py文件的文件编码

在本例中,我将“perros”替换为“gatos”并删除↑符号,请确保您要替换的文件保存在UTF-8编码中。

0

那么,你在这里展示的包含unicode字符U + 2191。但是你忘了说它是一个unicode字符串还是一个字节字符串,在后一种情况下字符串是什么。

如果它是一个unicode字符串(Python 3的字符串或Python 2的Unicode):

s.replace(u'\u2191', u'') 

的伎俩,无论是你的Python版本或字符集。

,如果它是一个字节的字符串(Python的2串或Python 3字节)

s.replace(u'\u2191'.encode(charset), b'') 

开了窍只要你知道你用什么字符集。

我总是prefere这种非ASCII字符输入的,这是因为字符集用来读取Python源在程序运行时可以不使用的字符集(那个什么# -*- coding= ... -*-线是为)

1

你可以这样做:

s = '''Lorem Ipsum 
        ↑ 
     The results really show what a poisonous''' 
clean_string = "".join([ch for ch in s if ch.isalnum() or ch in string.punctuation or ch.isspace()]) 

这将删除所有非标点符号/字母数字字符

-1

我不能完全肯定,如果你想只保留文字和数字,所以如果你只需要所有的特殊字符经历了一段时间我会建议这样的标识任何特殊字符而不仅仅是一个:

import re 
txt = 'Lorem Ipsum^The results really show what a poisonous' 
for x in filter(str.strip, re.findall("[^\w.]+", txt)): 
    txt = txt.replace(x,' ') 
    print(txt) 
+0

OP明确要求如何删除↑字符。 – mhawke

+0

你是对的,从这个意义上说,这个问题已经得到解答(我已经提出了相应的答案)。然而,主题是“从字符串中删除特殊字符”,所以我想我会给出更广泛的答案以防万一。 – dinos66

相关问题