+ 2
How can I replace all symbols in a string except the first and the last?
description of this task: Hi, Friend => H********d
15 ответов
+ 5
Try to apply list slicing with strings.
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2453/
+ 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
+ 3
Use a range.
+ 1
Andrex , Post your code here. It'll help others to understand what's your problem and what help you need.
+ 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.
+ 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!
0
i need to replace the first and last symbols on '*'
0
i need to create a lambda function that is something like this(but replaces all symbols without the first and the last):
0
lambda x = 'hi, Fri': ''.join(c if c in ', ' else '*' for c in x)
0
the first index is 0
the last index is -1 or the length-1 (of the string)
0
Just use slicing.Copy the string into a temp=string[1:len (string)-1] and perform the operation
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?
0
mystring = "Hi, Friend"
for x in range(1, len(mystring)-1):
mystring = mystring.replace(mystring[x], '*')
print(mystring)
- 1
Sousou, It works! But we need to replace also all spaces and punctuation marks. Expected:
Hi, Friend => H********d