从具有“ +”字符的字符串创建一个字符串列表。使用“ +”分隔列表

时间:2019-02-25 11:00:11

标签: python string if-statement string-formatting

我有一个示例输入字符串,如下所示:

med_str = 'Film-coated tablet + ALpha Chloro, Prolonged-release tablet + ALFU Dioxide'

我想创建一个用'+'分隔的字符串列表。预计产量:

med_str = ['Film-coated tablet', 'ALpha Chloro'], ['Prolonged-release tablet', 'ALFU Dioxide']

在某些情况下,可能只有一个'+'分隔的字符串。示例:

new_str = 'Tablet + DEFLAZo'

预期输出:

new_str = ['Tablet', 'DEFLAZo']

我该如何在python中使用if else来做到这一点,它应该处理所有情况,并在/不存在一个或多个带有'+'元素的情况下创建一个由逗号分隔的单独字符串列表字符串,并用逗号分隔。

3 个答案:

答案 0 :(得分:0)

尝试一下:

<?xml version="1.0" encoding="utf-8"?>
<TextView
      android:layout_width="match_parent"
      android:layout_height="200dp"
      app:autoSizeTextType="uniform"
      app:autoSizeMinTextSize="12sp"
      app:autoSizeMaxTextSize="100sp"
      app:autoSizeStepGranularity="2sp" />

med_str = [i.split(" + ") for i in med_str.split(", ")] # Gives output as list of lists.

答案 1 :(得分:0)

使用“先夹住(,)”如果成功,则会将列表拆分为具有两个字符串的串联列表,现在只需用(+)拆分即可得到“剩余结果”

med_str = 'Film-coated tablet + ALpha Chloro, Prolonged-release tablet + ALFU Dioxide'

final=[l.split("+") for l in med_str.split(",")]
print(final)

答案 2 :(得分:0)

假设您的字符串始终具有完整数目的巴黎,请按以下步骤操作:

med_str = 'Film-coated tablet + ALpha Chloro, Prolonged-release tablet + ALFU Dioxide'

cleaned = [s.strip() for s in med_str.replace('+',',').split(',')]
result = [[cleaned[i], cleaned[i+1]] for i in range(0, len(cleaned), 2)]
print(result)

输出:

[['Film-coated tablet', 'ALpha Chloro'], ['Prolonged-release tablet', 'ALFU Dioxide']]