Raja G
Raja G

Reputation: 6673

Explanation of `ch[:prefix_len%len(ch)]` in python program

I am looking at this python program and almost understood its flow but I am unable to understand ch[:prefix_len%len(ch)] in the following part:

else:
            prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
            suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]

Here is the context:

def banner(text, ch='=', length=78):
    if text is None:
        return ch * length
    elif len(text) + 2 + len(ch)*2 > length:
        # Not enough space for even one line char (plus space) around text.
        return text
    else:
        remain = length - (len(text) + 2)
        prefix_len = remain / 2
        suffix_len = remain - prefix_len
        if len(ch) == 1:
            prefix = ch * prefix_len
            suffix = ch * suffix_len
        else:
            prefix = ch * (prefix_len/len(ch)) + ch[:prefix_len%len(ch)]
            suffix = ch * (suffix_len/len(ch)) + ch[:suffix_len%len(ch)]
        return prefix + ' ' + text + ' ' + suffix

Could somebody please help me to understand this. Thank you.

Upvotes: 0

Views: 149

Answers (2)

Lindsay Ward
Lindsay Ward

Reputation: 479

Sure! ch[:prefix_len % len(ch)] is accessing a slice of the ch sequence starting from the beginning (since there's no value before the : and going to one character before the index defined by prefix_len % len(ch).

This value is prefix_len (defined earlier as the length of the prefix, not surprisingly) modulus the length of ch. (Think of it as the remainder left over after integer division of prefix_len / len(ch).

I ran the function like: print(banner("Hello everyone!", "1234")) and got: 123412341234123412341234123412 Hello everyone! 1234123412341234123412341234123 so you can see it's fitting the ch value (1234 in my case) in the space it has.

Upvotes: 1

willnx
willnx

Reputation: 1283

They're adding the remainder.

Say prefix = 10, and ch = '#&+'

If you just multiply ch by prefix_len / len(ch), you'll get 9, but you know you need 10.

So ch[:prefix_len % len(ch)] is just indexing into ch string for the remainder.

Make sense?

Upvotes: 1

Related Questions