Removing continuation characters in the middle of a string in Python

一笑奈何 提交于 2019-12-05 21:42:12
results_str.replace('\n', "") 

You're so close. The \ is an escape character in string literals, so you must either double it up, or use a raw string:

results_str.replace('\\n', "") 
results_str.replace(r'\n', "") 

Also remember that Python strings are immutable: replace() returns a new string, because the existing string cannot be modified. If you want to keep the changed string, you have to assign it to some name, such as the original name:

results_str = results_str.replace(r'\n', "")

Although you may want to process your data in a fashion that doesn't care about the newlines. That looks like JSON, so rather than trying to parse it yourself you should probably be using the Python json module.

This is a JSON response. Instead of trying to mess with the string, you should use the json module to parse the string:

import json
result = b'{\n   "destination_addresses" : ...'
obj = json.loads(obj.decode('utf-8'))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!