+ 2

How can I replace all symbols in a string except the first and the last?

description of this task: Hi, Friend => H********d

19th Mar 2020, 10:14 AM
Andrey Shintar
Andrey Shintar - avatar
15 Respostas
19th Mar 2020, 10:16 AM
Tibor Santa
Tibor Santa - avatar
+ 3
You can do it simpler: s = "Hi, friend" hidden = s[0] + '*' * (len(s) - 2) + s[len(s) - 1] print(hidden) But length of a string should be at least 2 characters
19th Mar 2020, 12:15 PM
andriy kan
andriy kan - avatar
+ 3
Use a range.
21st Mar 2020, 2:40 AM
Sonic
Sonic - avatar
+ 1
Andrex , Post your code here. It'll help others to understand what's your problem and what help you need.
19th Mar 2020, 10:26 AM
🇼🇳Omkar🕉
🇼🇳Omkar🕉 - avatar
+ 1
Use the enumerate function inside the join. It will give you the index of each letter too. Then you can compare this index with the string length in the ternary expression.
19th Mar 2020, 11:01 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Answer is: func = lambda x = 'hi, Fri': ''.join(x[c] if x[c] in '' for c in (0, len(x)-1) else '*' for c in range(len(x))) print(func()) Thanks for all a lot!
19th Mar 2020, 11:59 AM
Andrey Shintar
Andrey Shintar - avatar
0
i need to replace the first and last symbols on '*'
19th Mar 2020, 10:25 AM
Andrey Shintar
Andrey Shintar - avatar
0
i need to create a lambda function that is something like this(but replaces all symbols without the first and the last):
19th Mar 2020, 10:33 AM
Andrey Shintar
Andrey Shintar - avatar
0
lambda x = 'hi, Fri': ''.join(c if c in ', ' else '*' for c in x)
19th Mar 2020, 10:33 AM
Andrey Shintar
Andrey Shintar - avatar
19th Mar 2020, 10:54 AM
Sousou
Sousou - avatar
0
the first index is 0 the last index is -1 or the length-1 (of the string)
19th Mar 2020, 10:56 AM
Sousou
Sousou - avatar
0
Just use slicing.Copy the string into a temp=string[1:len (string)-1] and perform the operation
19th Mar 2020, 7:00 PM
Prakhar gurha
Prakhar gurha - avatar
0
But what if I want to complicate this task and to replace uppercase symbols, therefore I need to use a cycle and the isupper() method to get @***@***** from string 'Hi, Friend', or how?
20th Mar 2020, 10:48 AM
Andrey Shintar
Andrey Shintar - avatar
0
mystring = "Hi, Friend" for x in range(1, len(mystring)-1): mystring = mystring.replace(mystring[x], '*') print(mystring)
20th Mar 2020, 6:30 PM
rodwynnejones
rodwynnejones - avatar
- 1
Sousou, It works! But we need to replace also all spaces and punctuation marks. Expected: Hi, Friend => H********d
19th Mar 2020, 11:44 AM
Andrey Shintar
Andrey Shintar - avatar