Program outputs incorrect string format with join method

Viewed 38

I am trying to output in the format (a, b and c) from a function that should print common letters from 2 strings, but what I currently get is (a,b,and,c).


def task10(str1,str2):
    str1=str1.lower()
    str2=str2.lower()
    ch1=""
    ch2=""
    for i in str1:
        if i.isalpha():
            ch1+=i
    for k in str2:
        if k.isalpha():
            ch2+=k

    common = list(set([c for c in ch1 if c in ch2]))
    s=len(common)
    if s==0:
        common=['no common letters']
    common.sort()
    if s>1:
        common.insert(-1," and ")

    common= ', '.join(common)
    common = common.replace(', and ,', 'and')
    print(f'{common}')

task10("i like big cups","i cannot lie")
2 Answers

Do a string replace for ,and, with and to get the correct output.

def task10(str1,str2):
    str1=str1.lower()
    str2=str2.lower()

    badchars = ['$','@','%',';',':','!',"*"," ",'1',"2","3","4","5","6","7","8","9","0",'^','&','#','~','?','[]','{',']',"+",'=','-','_','-',",",'"',"'",'`',"|","\\",'(',')']

    for i in badchars:
        str1=str1.replace(i,"")
        str2=str2.replace(i,"")

    common = list(set([c for c in str1 if c in str2]))
    i=len(common)
    if i==0:
        common=['no common letters']
    common.sort()
    if i>1:
        common.insert(-1,"and")

    common= ','.join(common)
    common = common.replace(',and,', ' and ')
    print(f'{common}')

task10('icl!','i cannot lie!')

Output:

c,i and l

You can do this efficiently with set manipulation. Note that badchars is a set and not a list as in the original question.

badchars = {'$', '@', '%', ';', ':', '!', "*", " ", '1', "2", "3", "4", "5", "6", "7", "8", "9", "0", '^',
            '&', '#', '~', '?', '[', '{', ']', "+", '=', '-', '_', '-', ",", '"', "'", '`', "|", "\\", '(', ')', '£'}


def task10(str1, str2):
    match len(rv := (set(str1) & set(str2)) - badchars):
        case 0:
            return ''
        case 1:
            return rv.pop()
        case _:
            rv = list(rv)
            return ', '.join(rv[:-1]) + ' and ' + rv[-1]


print(task10('ic!', 'i cannot lie!'))

Output:

i, c and l
Related