从python中的字符串中剥离字符串的所有实例

时间:2013-04-16 19:39:39

标签: python

我有一些自定义API的结果,我需要解析和清理。下面是一个存储为变量的示例输出。

(DeviceConnectionInformation){
     DeviceName = "device1"
     ClientName = "ourclient"
     RegionName = "west"
     PrimaryIP = "1.1.1.1"
     OsVersionName = "Microsoft Windows 7 Enterprise"
     AccessMethod = None
     AccessIP = None
     Port = None
  },
  (DeviceConnectionInformation){
     DeviceName = "device2"
     ClientName = "ourclient"
     RegionName = None
     PrimaryIP = "1.1.1.2"
     OsVersionName = "Microsoft Windows 7 Enterprise"
     AccessMethod = None
     AccessIP = None
     Port = None

我需要删除可能发生的“(DeviceConnectionInformation){”和“}”的任何和所有情况,并保留以下格式:

DeviceName = "device1"
ClientName = "ourclient"
RegionName = "west"
PrimaryIP = "1.1.1.1"
OsVersionName = "Microsoft Windows 7 Enterprise"
AccessMethod = None
AccessIP = None
Port = None

DeviceName = "device2"
ClientName = "ourclient"
RegionName = None
PrimaryIP = "1.1.1.2"
OsVersionName = "Microsoft Windows 7 Enterprise"
AccessMethod = None
AccessIP = None
Port = None

2 个答案:

答案 0 :(得分:1)

假设您的数据是字符串形式,您可以通过将其替换为空来删除文字字符串:

val = val.replace("(DeviceConnectionInformation){", "")
val = val.replace("},", "")

但是,我对此持谨慎态度,尤其是第二种情况,因为它不关注上下文。例如,如果},在您引用的字符串中出现数据,则仍会将其删除。

答案 1 :(得分:0)

怎么样

for x in ("DevicConnectionInformation{\n", "},", "     "):
    data = data.replace(x, "")
如果例如},出现在值中,则会遇到麻烦。