2024-09-29 08:22:25 发布
网友
我有以下代码:
text = 'hello world 2,000 3,000' text = text.replace(' ', '|') print text
输出为:
我想用“|”分隔,但我希望输出分为三列。我不想用词来分隔,只想用数字来分隔:
hello world|2,000|3,000
我怎么能做到呢?在
如果您不需要正则表达式,请执行以下操作: 这是假设您有许多行输入,并将它们全部放入一个列表列表中。 它返回一个列表列表,其中每个元素都是正确解析的字符串。在
这只假设您的字段由一个空格隔开,并且您不希望在前两个字段之间使用管道。在
# one line of input text = 'hellow world 1,000 2,000' testlist = text.split(' ') # all your input list_of_all_text = [testlist] + [testlist] + [testlist] first_feilds = map(lambda x: x[0]+' '+x[1],list_of_all_text) last_feilds = map(lambda x: x[2:],list_of_all_text) all_feilds = map(lambda x,y: [x]+y,first_feilds,last_feilds) parsed_feilds = map(lambda x: '|'.join(x),all_feilds) print parsed_feilds
更简洁易读:
有三个字段用空格隔开,第一个字段也可能包含空格。您可以将rsplit与maxplit参数一起使用,将字符串从右侧分成三部分。在
rsplit
text = 'hello world 2,000 3,000' # Split at the two rightmost spaces, so that # the leftmost of the three fields can contain spaces parts = text.rsplit(' ', 2) # ['hello world', '2,000', '3,000'] result = '|'.join(parts) # 'hello world|2,000|3,000'
使用正则表达式替换:
import re text = 'hello world 2,000 3,000' print re.sub(r'\s(\d)', '|\\1', text)
这只为前面有空格和数字的内容插入管道标记。在
如果您不需要正则表达式,请执行以下操作: 这是假设您有许多行输入,并将它们全部放入一个列表列表中。 它返回一个列表列表,其中每个元素都是正确解析的字符串。在
这只假设您的字段由一个空格隔开,并且您不希望在前两个字段之间使用管道。在
更简洁易读:
^{pr2}$有三个字段用空格隔开,第一个字段也可能包含空格。您可以将
rsplit
与maxplit参数一起使用,将字符串从右侧分成三部分。在使用正则表达式替换:
这只为前面有空格和数字的内容插入管道标记。在
相关问题 更多 >
编程相关推荐