【问题标题】:Convert dict into String and then split specific portion of string将 dict 转换为字符串,然后拆分字符串的特定部分
【发布时间】:2019-07-05 19:50:26
【问题描述】:

1) 我有输入字符串,用逗号分隔,服务器作为键。有一个 userDefined 方法,它将那些逗号分隔的字符串转换为键,并用 dict 中的值填充。

```
input_string=("'123','456'")
#userdefined method, which returns 
a_dict=convertIntoDict(input_string)

print (type (a_dict))
<type 'dict'>
```

上述dict的取值如下:

print a_dict
{'123': <Merc:/Tire/Merc/aus>, '456': <Honda:/Tire/Honda/ind>}

我想循环遍历 dict ,需要输出不带引号和逗号的字符串,比如 输出:

```Merc/aus, Honda/ind``` 

for ind_values in a_dict.values():
    s_i=str(ind_values)
    test_s=s_i.split("Instruments/", 1)[1].split(">",1)[0]
    print("attempt 1")
    print(test_s+",")
    test_f +=test_s+","

我想循环遍历 dict ,需要输出不带引号和逗号的字符串,比如 输出:

Merc/aus, Honda/ind

相反,它显示以下内容,

Merc/aus, 
Honda/ind

【问题讨论】:

    标签: python string dictionary split


    【解决方案1】:

    将 print(test_s+",") 改为 print(test_s, end=", ")

    【讨论】:

      【解决方案2】:

      如果我正确理解了您的请求,下面的代码应该可以工作。

      a_dict = {'123': '<Merc:/Tire/Merc/aus>', '456': '<Honda:/Tire/Honda/ind>'}
      
      result = list()
      
      for ind_values in a_dict.values():
          s_i=str(ind_values)
          item = s_i.split("Tire")[1][:-1]
          result.append(item)
      
      print(", ".join(result))
      

      它产生以下输出:

       /Merc/aus, /Honda/ind
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-25
        • 2019-01-13
        • 1970-01-01
        • 1970-01-01
        • 2019-10-10
        • 2021-02-06
        相关资源
        最近更新 更多