python -- 字符串的替换

【问题描述】

python中的空值是用None来实现的,但是在实现java的指标上线时,无法解析我的字符串中的None字符,所以我需要将字符串中的None转化为null。

即:字符串转化:"None" -> "null"

【问题解决】

两种方法:

1.利用replace函数:

string_old.replace(str_from,str_to)

string_old就是你要更改的字符串,str_from是你需要替换的子字符串,str_to是你要转换成的子字符串。

举例:

string_old = "我喜欢你!"
string_new = string_old.replace("喜欢","讨厌")
string_new

返回结果:


2.利用正则化函数

import re
a = {'test_str':"[{'c_bill_record_deal_time':" '2018-06-22'",'c_bill_record_description': '汇缴', 'c_bill_record_income': 480.0, 'c_user_info_corporation_ratio': None, 'c_user_info_customer_ratio': None, 'city': '厦门', 'corporation_income': None, 'create_time': '2018-07-06 09:26:08', 'customer_income': None, 'lend_request_id': None, 'month': '2018-06', 'task_id': 'None', 'user_id': 'None'}]"}
string_old = a['test_str']
strinfo = re.compile('None')
string_new = strinfo.sub('null',string_old)
string_new

返回结果:


发现None确实转换成null了!

如果我们对同样的数据,采用replace方法

a = {'test_str':"[{'c_bill_record_deal_time':" '2018-06-22'",'c_bill_record_description': '汇缴', 'c_bill_record_income': 480.0, 'c_user_info_corporation_ratio': None, 'c_user_info_customer_ratio': None, 'city': '厦门', 'corporation_income': None, 'create_time': '2018-07-06 09:26:08', 'customer_income': None, 'lend_request_id': None, 'month': '2018-06', 'task_id': 'None', 'user_id': 'None'}]"}
string_old = a['test_str']
string_new = string_old.replace("喜欢","讨厌")
string_new

返回的结果为:


发现,并没有转化成功!!!!!!!

所以,从暂时的情况来看,正则化方法稳定性更好一些~

(仅供个人学习,不负任何责任~~~~~~~~~~~)

猜你喜欢

转载自blog.csdn.net/august1226/article/details/80983498