-2
- 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:], '*')
???– Augusto Vasques
no, it is returning the full string, ie ta returning 'b*', and the correct one was to return 'ba**le
– Pinguim
@Augustovasques
– Pinguim
s[:1:1]
returns the first character of the string (it is the same ass[0]
) ands[: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, yourreplace
is taking everything from the second character on (s[1:]
) and switching to an asterisk– hkotsubo
If I understand correctly, just do
s[0] + s[1:].replace(s[0], '*')
-s[0]
is the first character ands[1:]
takes everything from the second (and in this passage you change the occurrences of the first character by asterisk)– hkotsubo
Thanks for the help, I will follow the advice!! little thing I read, already opened my mind a lot!!!
– Pinguim
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
– Pinguim