Home > front end >  I'm trying to write a code in which the character "|" is inbetween each letter howeve
I'm trying to write a code in which the character "|" is inbetween each letter howeve

Time:10-20

I have written the code below in which each after each letter there will be a |:

def art(word):
    numoflet = len(word)
    word = word.upper()

    for Y in range(numoflet - 1, 0, -1):
        if word[Y:].count(word[Y]) >= 2:
            pass
        else:
            let = word[Y]
            let1 = let   "|"
            word = word.replace(let, let1)

    word = "|"   word
    pat = ""

    numoflet = len(word)
    for X in range(numoflet, 0, -1):
        if X % 2 == 0:
            pat = pat   "-"
        else:
            pat = pat   " "

    print("\n"   pat   "\n\n"   word   "\n\n"   pat)

word = "Craig'n'Dave"
art(word)

My intended output is;

 - - - - - - - - - - - - 

|C|R|A|I|G|'|N|'|D|A|V|E|

 - - - - - - - - - - - - 

However after some letters (C, N, D below) it does not produce the | shown in the result below:

- - - - - - - - - - - 

|CR|A|I|G|'|N'|DA|V|E|

- - - - - - - - - - - 

Why is this happening?

CodePudding user response:

Two reasons your routine is not doing what you expect.

  1. replace() replaces all occurrences, so when you replace the A in DAVE you are also replacing the A in CRAIG, which really messes things up.

  2. Your range is not including the first letter "C". The "stop" parameter is not included in the range.

During debugging a well placed "print()" can help you solve your problem. If you print(Y) each time through the loop you will see that the loop stops when Y=1, instead of when Y=0.

If you print(word) each time through the loop you will see the error when the loop handles the A.

CodePudding user response:

You can use join method that join list of string with another string. First list("Craig'n'Dave") create ['C', 'r', 'a', 'i', 'g', "'", 'n', "'", 'D', 'a', 'v', 'e'] then you join each elements with "|"

word="Craig'n'Dave"
def art(word, title_rep=" -", sep="|"):
    result = sep.join(list(word)).upper()
    head = title_rep * (len(result) // len(title_rep))   title_rep[:len(result) % len(title_rep)]
    return f"{head}\n{result}\n{head}"

print(art(word))

Output:

 - - - - - - - - - - -                                                                                                  
C|R|A|I|G|'|N|'|D|A|V|E                                                                                                 
 - - - - - - - - - - - 
  • Related