[英]About split (Python function)
My question is about split function我的问题是关于拆分 function
I have a tuple:我有一个元组:
name = 'test_1_1', 'test_1_2', 'test_1_3-4-5'...
I want to get to something like this:我想得到这样的东西:
['test_1_1', 'test_1_2', 'test_1_3', 'test_1_4', 'test_1_5']
How could I do that?我怎么能那样做?
Your question is pretty invalid but,您的问题非常无效,但是,
Does this work for you:这对你有用吗:
names = 'test_1_1', 'test_1_2', 'test_1_3-4-5'
res = []
for name in names:
if '-' not in name:
res.append(name)
continue
parts = name.split('_')
for sub in parts[2].split('-'):
res.append(f'{parts[0]}_{parts[1]}_{sub}') # This is what makes sense to me but maybe you want the following:
# res.append(f'{parts[0]},{parts[1]},{sub}')
print(res)
output: output:
['test_1_1', 'test_1_2', 'test_1_3', 'test_1_4', 'test_1_5']
Assuming that your string
is indeed a tuple
, you can use:假设您的string
确实是一个tuple
,您可以使用:
import re
name = 'test_1_1', 'test_1_2', 'test_1_3-4-5'
new_name = [re.split(r"[_-]", x) for x in name]
# [['test', '1', '1'], ['test', '1', '2'], ['test', '1', '3', '4', '5']]
Or, and because I didn't fully understand your question, you may need:或者,由于我没有完全理解您的问题,您可能需要:
new_name = [re.sub(r"[_-]", ",", x) for x in name ]
# ['test,1,1', 'test,1,2', 'test,1,3,4,5']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.