Doubt about substitutions in python replace method, how to better access the lists?

Asked

Viewed 40 times

-2

  1. fix_start

Given a string s, return a string where all occurrences of the first character of s were replaced by '*', except for the first.

Example: 'Babble' returns 'ba**le'

Assume the string is 1 or larger.

Tip: s.replace(Stra, strb) returns a version of string s where all instances of Stra have been replaced by strb.

def fix_start(s):
    # +++ SUA SOLUÇÃO +++
    if s[:2] == s[:1:1]:
        return s.replace(s[1:], '*',)
    


# --- Daqui para baixo são apenas códigos auxiliáries de teste. ---

def test(f, in_, expected):
    """
    Executa a função f com o parâmetro in_ e compara o resultado com expected.
    :return: Exibe uma mensagem indicando se a função f está correta ou não.
    """
    out = f(in_)

    if out == expected:
        sign = '✅'
        info = ''
    else:
        sign = '❌'
        info = f'e o correto é {expected!r}'

    print(f'{sign} {f.__name__}({in_!r}) retornou {out!r} {info}')


if __name__ == '__main__':
    # Testes que verificam o resultado do seu código em alguns cenários.
    test(fix_start, 'babble', 'ba**le')
    test(fix_start, 'aardvark', 'a*rdv*rk')
    test(fix_start, 'google', 'goo*le')
    test(fix_start, 'donut', 'donut')
  • You wrote all this to ask if there’s a better way to write this s.replace(s[1:], '*') ???

  • no, it is returning the full string, ie ta returning 'b*', and the correct one was to return 'ba**le

  • @Augustovasques

  • s[:1:1] returns the first character of the string (it is the same as s[0]) and s[:2] returns the first two characters of the string, so these expressions will never be equal (except if the string has less than 2 characters). In its another question I already left one link explaining how the Slices, I suggest you read until you understand what you are doing (without irony, it is sincere advice). In this case, your replace is taking everything from the second character on (s[1:]) and switching to an asterisk

  • 2

    If I understand correctly, just do s[0] + s[1:].replace(s[0], '*') - s[0] is the first character and s[1:] takes everything from the second (and in this passage you change the occurrences of the first character by asterisk)

  • Thanks for the help, I will follow the advice!! little thing I read, already opened my mind a lot!!!

  • I was able to do it this way, but I still don’t think it was very simplified: a = s.replace(s[:1],', 1) b = a.replace(s[:1], '*') Return s[:1] + b

Show 2 more comments

1 answer

0

def fix_start(palavra: str) -> str:
    primeira_letra = palavra[0]
    restante_da_palavra = palavra[1:]

    nova_palavra = primeira_letra + restante_da_palavra.replace(primeira_letra, '*')

    return nova_palavra 

print(fix_start('babble'))


Return: ba**le

I hope this helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.