1

I wanted to cover up a word. I get the user input.

user_input = input("Enter input: ")

After getting this value I want to represent it in asterisks.

Like if the user_input is "password" I want ********. Basically, the same number of characters as the original input.

My code for this is:

shadowed = ''
for i in range(len(user_input)):
    shadowed += '*'  

So I get shadowed as my desired keyword.

However, my editor highlights the i and says: Unused variable 'i'pylint(unused-variable)

Would this be an issue? Or do I have to fix it?

  • 3
    They're not a *problem* exactly, but the convention is to use `_` to indicate that it's *intentionally* unused. Or just do `shadowed = "*" * len(user_input)`. – jonrsharpe Nov 02 '20 at 08:02
  • 1
    question already answered on SO [here](https://stackoverflow.com/q/24928585/13714870) – Marc Nov 02 '20 at 08:06
  • you can download a module named getpass it converts the keyword to '*' –  Nov 02 '20 at 08:10
  • @Rice that's part of the standard library, and doesn't echo anything (so it doesn't leak the length either): https://docs.python.org/3/library/getpass.html – jonrsharpe Nov 02 '20 at 08:18

3 Answers3

2

No problem with your code.
But in addition, you can use:

shadowed_password = "*" * len(user_input)

Which is more Pythonic. To deal with the lint error, change your code to:

for _ in user_input:

Because i in never used. for i in user_input Is not Pythonic, when i is never used.

MuxAte
  • 66
  • 1
  • 6
1

In python, you use underscores _ for unused variables.

In your case:

shadowed = ''
for _ in range(len(user_input)):
    shadowed += '*'  

Now you shouldn't get any lint errors anymore.

1

There are a couple of things here.

To begin with, the convention is to use something like _ for a throwaway variable like this. So it would be:

for _ in range(len(user_input)):

This should get rid of the warning.

Asides from that, since you're just performing something for each element, why not change it to

for _ in user_input:

The combination of the two is not only shorter, it makes it clearer that you just want to perform something for each element, not really caring about the index.

You could even use something shorter like

''.join('*' for _ in user_input)

or just

'*' * len(user_input)

The combination of the two is not only shorter, it makes it clearer that you just want to perform something for each element, not really caring about the index.

Ami Tavory
  • 74,578
  • 11
  • 141
  • 185