我正在尝试用不同的子字符串替换子字符串的所有实例。我执行此操作的字符串有时可能是nan <class 'float'>
。
我当前的代码是x.replace('\n\n', '\n')
。当&#39; x&#39;变量是一个字符串。但是,&#39; x&#39;也可以是一个南。使用nan值时,将返回错误AttributeError: 'float' object has no attribute 'replace'
。
我正在寻找像x.replace('\n\n', '\n', on_float='ignore')
这样的内容。这样调用x.replace('\n\n', '\n')
,其中x为<class 'float'>
将返回一个未更改的变量&#39; x&#39;。
答案 0 :(得分:2)
Python的异常系统非常诱人:
try:
x = x.replace('\n\n', '\n')
except AttributeError:
pass
通过这种方式,不仅浮动,而且没有.replace()
方法的所有内容都将被安全地忽略,无论它是什么。
或者把它包起来:
def universal_replace(x, a, b):
try:
return x.replace(a, b)
except AttributeError:
return x
然后你可以安全地浏览所有内容:
x = universal_replace(x, '\n\n', '\n')
您还可以在except
子句中实现自己的代码,以更好地处理其他数据类型。
答案 1 :(得分:0)
在执行替换操作之前,您可以检查您的元素是否为字符串!
>>> def check_and_replace(x, f, t):
... if isinstance(x,str):
... return x.replace('\n\n', '\n')
... return x
...
>>> check_and_replace('5', '\n\n', '\n')
'5'
>>> check_and_replace(5, '\n\n', '\n')
5
>>> check_and_replace(type('5'), '\n\n', '\n')
<type 'str'>