I need to write some code for making a double space between 1-2 words, triple space between 2-3, then double again followed by triple and so on.

I came up with this code:


a = 'one two three four'
and I want to get this: "one two three four"

print ' '.join(a.split()[0:2]), ' ', ' '.join(a.split()[2:3])

this partially works because -

it does not return the last string from the list 'four' , i tired [2:0], [-1:-3], but it did not work

and the whole code is not automated at all - the spaces are specified manually

if anybody has a solution I would like to hear thanks!

Recommended Answers

All 2 Replies

This is a way to do it without slicing:

# separate words with alternating 2 and 3 spaces
# simply alternate between odd and even count

s = 'one two three four five'

space = " "
new = ""
count = 1
for c in s:
    # count & 1 is True for odd count
    if c == space and count & 1:
        # use 2 spaces
        c = space*2
        new += c
        count += 1
    elif c == space and not count & 1:
        # use 3 spaces
        c = space*3
        new += c
        count += 1
    else:
        new += c

print new  # one  two   three  four   five
commented: nice help +7

Hey Lardmeister, you must be pulling As in your Science/Python classes. Nice clean code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.