我的字典如下:
'{\n "bindings": [\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/browser"\n },\n {\n "members": [\n "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com",\n "user:rohithmn03@gmail.com"\n ],\n "role": "roles/owner"\n },\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/viewer"\n }\n ],\n "etag": "BwVvsH-HhI0=",\n "version": 1\n}\n'
我需要从中删除\n
;
但是strip()
无法解决问题。
我们还有其他方法可以将其删除吗?!!?
关于, 罗希斯
答案 0 :(得分:1)
鉴于那里有一个JSON字符串,您可能应该使用json
模块:
import json
my_dict = json.loads('{\n "bindings": [\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/browser"\n },\n {\n "members": [\n "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com",\n "user:rohithmn03@gmail.com"\n ],\n "role": "roles/owner"\n },\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/viewer"\n }\n ],\n "etag": "BwVvsH-HhI0=",\n "version": 1\n}\n')
然后将其用作实际词典,并可以根据需要进行操作。如果要不使用换行符进行打印,则可以:
print(my_dict)
或者您可以将其用作字典,具体取决于您实际尝试删除换行符的方式。
如果您确实有该字符串,并且只想摆脱其中的换行符,则可以使用.replace
:
'{\n "bindings": [\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/browser"\n },\n {\n "members": [\n "serviceAccount:admin-user@linuxacademy-3.iam.gserviceaccount.com",\n "user:rohithmn03@gmail.com"\n ],\n "role": "roles/owner"\n },\n {\n "members": [\n "user:rohithmn3@gmail.com"\n ],\n "role": "roles/viewer"\n }\n ],\n "etag": "BwVvsH-HhI0=",\n "version": 1\n}\n'.replace('\n', '')