Python 字符串中的多个分隔符
我有这种绳子。我面临的问题是将其拆分为两个列表。输出大致如下:Python 字符串中的多个分隔符,python,python-3.x,list,Python,Python 3.x,List,我有这种绳子。我面临的问题是将其拆分为两个列表。输出大致如下: text="Brand.*/Smart Planet.#/Color.*/Yellow.#/Type.*/Sandwich Maker.#/Power Source.*/Electrical." 有没有解决方法。您可以使用正则表达式拆分文本,并在循环中填充列表。 name = ['Brand','Color','Type','Power Source'] value = ['Smart Plane','Yellow','Sandw
text="Brand.*/Smart Planet.#/Color.*/Yellow.#/Type.*/Sandwich Maker.#/Power Source.*/Electrical."
有没有解决方法。您可以使用正则表达式拆分文本,并在循环中填充列表。
name = ['Brand','Color','Type','Power Source']
value = ['Smart Plane','Yellow','Sandwich Maker','Electrical']
使用regex可以保护代码不受无效输入的影响
name = []
value = []
text = text.split('.#/')
for i in text:
i = i.split('.*/')
name.append(i[0])
value.append(i[1])
这是一种使用
re.split
和list
切片的方法
Ex:
import re
name, value = [], []
for ele in re.split(r'\.#\/', text):
k, v = ele.split('.*/')
name.append(k)
value.append(v)
>>> print(name, val)
['Brand', 'Color', 'Type', 'Power Source'] ['Smart Planet', 'Yellow', 'Sandwich Maker', 'Electrical.']
import re
text="Brand.*/Smart Planet.#/Color.*/Yellow.#/Type.*/Sandwich Maker.#/Power Source.*/Electrical."
data = [i for i in re.split("[^A-Za-z\s]+", text) if i]
name = data[::2]
value = data[1::2]
print(name)
print(value)
输出:
import re
name, value = [], []
for ele in re.split(r'\.#\/', text):
k, v = ele.split('.*/')
name.append(k)
value.append(v)
>>> print(name, val)
['Brand', 'Color', 'Type', 'Power Source'] ['Smart Planet', 'Yellow', 'Sandwich Maker', 'Electrical.']
import re
text="Brand.*/Smart Planet.#/Color.*/Yellow.#/Type.*/Sandwich Maker.#/Power Source.*/Electrical."
data = [i for i in re.split("[^A-Za-z\s]+", text) if i]
name = data[::2]
value = data[1::2]
print(name)
print(value)
text=“Brand.*/Smart Planet.#/Color.*/Yellow.#/Type.*/Sandwich Maker.#/Power Source.*/Electrical。”
名称=[]
值=[]
单词=“”
对于范围内的i(len(text)):
温度=i
如果文本[i]!='。'和文本[i]!='/'和文本[i]!='*'和text[i]!='#':
word=word+''.join(文本[i])
elif temp+1您当前的非最佳解决方案是什么?@Sayse抱歉我问错了问题。我更新了它