在Python中删除字符串中间的连续字符 [英] Removing continuation characters in the middle of a string in Python
问题描述
Google maps API的标准返回值如下所示-从字节转换为字符串后:
The standard return value from the Google maps API looks like this - after conversion from bytes to a string:
b'{\n "destination_addresses" : [ "Washington, DC, USA" ],\n "origin_addresses" : [ "New York, NY, USA" ],\n "rows" : [\n {\n "elements" : [\n {\n "distance" : {\n "text" : "370 km",\n "value" : 369720\n },\n "duration" : {\n "text" : "3 hours 48 mins",\n "value" : 13672\n },\n "status" : "OK"\n }\n ]\n }\n ],\n "status" : "OK"\n}\n'
为了进一步处理,我想先删除所有换行符.但是,我不知道该怎么做
In order to process is any further, I would like to remove all the line break characters first. However, I don't know how to do it
results_str.replace('\n', "")
不起作用,即由于行继续符,它返回相同的字符串而不替换'\ n'.
won't work, .i.e., it returns the same string without replacing the '\n's, because of the line continuation character.
当我将反斜杠加倍时,也会发生同样的事情
Same thing happens when I double the backslash
results_str.replace('\\n', "")
有什么提示吗?
推荐答案
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', "")
还请记住,Python字符串是不可变的:replace()
返回一个新字符串,因为无法修改现有字符串.如果要保留更改后的字符串,则必须将其分配给某些名称,例如原始名称:
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', "")
尽管您可能希望以不关心换行符的方式处理数据.看起来像JSON,所以您可能不应该尝试自己解析它,而应该使用Python json
模块.
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.
这篇关于在Python中删除字符串中间的连续字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!