简体   繁体   中英

Python, Add + between every third letter

I want be able to add a plus sign (+) for every third letter. For instance,

sequence = ABCDEF

ABC + DEF

I've tried Str.join and it works sorta, but I want it to add a plus sign every third letter.

This is what I have so far.

s = sequence
a = (' + '.join(s))

You could try something like this:

'+'.join(sequence[i:i+3] for i in range(0,len(sequence),3))

Basically what this does is, first, get a sequence of numbers at indices at multiples of 3 using range: range(0,len(sequence),3)

Next, find substrings of length 3 starting from every index: [sequence[i, i+3] for i in range...]

Finally, join these substrings with a '+': '+'.join(...)

Hope this helps.

''.join([your_string[n] if n%3 != 2 else your_string[n]+' + ' for n in range(len(your_string))])

比上一个答案稍微复杂一点,但基本上它创建了一个字符串,其中每个字符都与原始字符串相同,除了每三个字符,它被添加' + '

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM