我有一个用例,我需要在python字典中传递一个具有半冒号和冒号的值。但它给了我一个语法错误。如果将值括在双引号而不是传统的单引号中,则似乎不会发生这种情况。有没有办法强加那个?或者,其他一些工作?
这是错误 -
props = {'creds1':'UserListings;service;SomeValue;Username:Mohan;Password:passkey123','creds2':''UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123'}
文件“”,第1行 monProps = {'creds1':'UserListings; service; SomeValue; Username:Mohan; Password:passkey123','creds2':''UserListings2; service; SomeValue2; Sample:Sikander; Password:passkey123'} ^ SyntaxError:语法无效
提前致谢!
答案 0 :(得分:0)
对特殊字符使用escape:
props = {'creds1':'UserListings;service;SomeValue;Username:Mohan;Password:passkey123','creds2':'\'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123'}
print(props)
输出:
{'creds1': 'UserListings;service;SomeValue;Username:Mohan;Password:passkey123', 'creds2': "'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123"}
答案 1 :(得分:0)
这对我来说很好用:
props = {'creds1': 'UserListings;service;SomeValue;Username:Mohan;Password:passkey123',
'creds2': 'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123'}
或者,如果你的文字中真的有引号,你可以这样逃避:
props = {'creds1': 'UserListings;service;SomeValue;Username:Mohan;Password:passkey123',
'creds2': '\'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123'}
或者,在字符串中只使用单引号,如你所提到的双引号将起作用:
props = {"creds1": "UserListings;service;SomeValue;Username:Mohan;Password:passkey123",
"creds2": "'UserListings2;service;SomeValue2;Sample:Sikander;Password:passkey123"}