Using Str.replace In A For Loop
I am working on an assignment that is asking me to change the below code so that line 4 uses str.isalnum and lines 5-7 become uses only one line using str.replace. s = 'p55w-r@d' r
Solution 1:
Just add the else part and you are done :
s = 'p55w-r@d'
result = ''
for c in s:
if(c.isalnum() == False):
result += c.replace(c,'*')
else:
result +=c
print(result)
p55w*r*d
Solution 2:
I have idea how to make same in 2 strings:
s = 'p55w-r@d'
print(''.join(map(lambda x: x if x.isalnum() else '*', s)))
OUT:
p55w*r*d
Solution 3:
The closest thing to meet your assignment's requirements while still making sense would be:
s = 'p55w-r@d'
result = s # Note the change here
for c in set(s): # set(..) is not strictly necessary, but avoids repeated chars
if not c.isalnum():
result = result.replace(c, '*')
Solution 4:
you can use if else after equal.
s = 'p55w-r@d'
result = ''
for c in s:
result += '*' if(c.isalnum() == False) else c
print(result)
>>>p55w*r*d # output
Post a Comment for "Using Str.replace In A For Loop"