使用不同的分隔符加入字符串

时间:2017-06-02 13:04:56

标签: python python-2.7

我想加入一个字符串,但偶数和奇数情况下有两个不同的分隔符。

我有这个清单:

l = [1,2,3,4,5,6,7,8,9]

我需要像这样加入:

1 || 2 || \n 3 ||  4 || \n 5 || 6 || \n 7 ||  8 || \n 9 

所以在每两个元素之后添加一个额外的换行符。

5 个答案:

答案 0 :(得分:4)

加入每两个元素,然后加入结果:

' || \n '.join([' || '.join([str(v) for v in l[i:i + 2]]) for i in range(len(l))])

或分为两个表达式:

paired = [' || '.join([str(v) for v in l[i:i + 2]]) for i in range(len(l))]
final = ' || \n '.join(paired)

后者对预期输出的改变效果更好。

演示:

>>> ' || \n '.join([' || '.join([str(v) for v in l[i:i + 2]]) for i in range(len(l))])
'1 || 2 || \n 2 || 3 || \n 3 || 4 || \n 4 || 5 || \n 5 || 6 || \n 6 || 7 || \n 7 || 8 || \n 8 || 9 || \n 9'

答案 1 :(得分:0)

类似的东西?

' || '.join(str(n) if n % 2 else '\n ' + str(n) for n in l)

答案 2 :(得分:0)

我制作了这个小剧本:

l = [1,2,3,4,5,6,7,8,9]
ret=""

for i in l:
    ret=ret + str(i);
    if i != 9:
        ret = ret + " || ";
    if i % 2 == 0:
        ret = ret + "\n ";
ret

```

答案 3 :(得分:0)

这是一个更动态的版本,带有评论:

l = [1,2,3,4,5,6,7,8,9]
ret=""

for i in l:
    ret=ret + str(i);
    # Add double pipe except for the last occurence
    if i != l[-1]:
        ret = ret + " || ";
    # Every 2 values, go to newline
    if i % 2 == 0:
        ret = ret + "\n ";
ret

答案 4 :(得分:0)

Hey guys am just a beginner in python but i tried to come up with a code for that question above i hope it is helpful somehow.
l = [1,2,3,4,5,6,7,8,9]
lst = []
lst_odd = []
delimeter1 = '| |'
delimeter2 = "/n"
count = 0
for num in l:
    if count == 0:
        x = str(num)
        lst.append(x)
        count += 1
    else:
        if num % 2 == 0:
            y = str(num)
            lst.append(y)
        else:
            z = str(num)
            lst_odd.append((delimeter2+z))
    if count == 2:
            break
main = [lst[0],lst[1],lst_odd[0],lst[2],lst_odd[1],lst[3],lst_odd[2],lst[4],lst_odd[3]]
s = delimeter1.join(main)
print(s)