So i'm working on this program for my gaming buddies in rust, the whole premise is to automate checking if our current codelock pin is strong or not. I want to use a list of the most common 4 digit pin codes and first check if the specified pin is in the list and if so what line is it at.
I coded the string download for the text file with requests but then realized i had no clue what i was doing! If anyone could even point towards some developer docs i would be forever greatful!
Here is the code i have so far:
import requests
pin = input('Code (4 Digit Numerical PIN): ')
url = 'https://raw.githubusercontent.com/xshonda/The-List/main/codes.txt'
list = requests.get(url).text
CodePudding user response:
Well, my first advice would be to not override builtins in Python. For example list = ...
is a bad practice in Python because later on the code you might want to create an new list with list()
, however that will then fail as the builtin name has been shadowed.
That said, it looks like the .text
attribute actually returns a string, so you actually have a new-line separated list of numeric values, as a str
value. To convert it to a list of pin's, you can use str.splitlines
method to split the string on the newline character, as shown below. Then you can find the index of the pin in the list using list.index
, but note that the index method raises an error if the list doesn't contain the specified pin within it, so we'll likely need some validation logic to handle such a case as well.
import requests
url = 'https://raw.githubusercontent.com/xshonda/The-List/main/codes.txt'
lines = requests.get(url).text
list_of_lines = lines.splitlines()
print(list_of_lines)
# now find index of pin in the list
pin = '1212'
try:
idx = list_of_lines.index(pin)
except ValueError: # pin is not in list
idx = -1
print('The specified PIN was not found in the list.')
else:
print(f'The index of the PIN ({pin}) in the list is: {idx}')
Output:
['1234', '1111', '0000', '1212', ...]
The index of the PIN (1212) in the list is: 3
NB: List indices (or rather indices in general) are zero-indexed in Python, however line numbers are actually one-indexed, since they start from line number 1. Therefore, you'll likely have to add 1 to the index -- assuming the PIN is found in the list -- to get the line number where the PIN appears in the text file.
CodePudding user response:
Here is the code to print which line pin is in:
from urllib.request import urlopen
pin = input('Code (4 Digit Numerical PIN): ')
url = 'https://raw.githubusercontent.com/xshonda/The-List/main/codes.txt'
f = urlopen(url)
for index, line in enumerate(f.readlines()):
line = str(line)
if pin in line:
print(f"line number {index 1}")
For example if pin is 4354 the output:
Code (4 Digit Numerical PIN): 4354
line number 1587