Python: 3 - make string after found keywords a variable? - python-3.x

I'm trying to find an elegant (easy) way of saving a sub-string in a string as a variable if i don't know what the word will be, but i do know what the four words before it are.
If the string is ("reset the password for johnny.mnemonic"), i need to be able to store the string johnny.mnemonic after i've found the substring? But how?
string = " will you reset password for johnny.mnemonic please"
substring = "reset password for"
if string.find(substring) is not -1:
print("i found the substring to request password reset")
#now add the next sub-string to as a variable here, user should be be next string over
else:
print("sorry, no request found.")

Maybe this is suitable solution for your situation:
cstring = " will you reset password for johnny.mnemonic please"
substring = "reset password for"
if substring in cstring:
words = cstring.split()
person = words[words.index('for')+1]
else:
person = False
if person:
#do stuff

input_string = " will you reset password for johnny.mnemonic please"
substring = "reset password for " # keep in mind the ending space
first_index = input_string.find(substring)
if first_index != -1: # if found
last_index = first_index + len(substring)
print(input_string[last_index:].split(" ")[0]) # split into words and get the first word
Output:
johnny.mnemonic
Basically it will search for "reset password for " and then obtain the next word after the substring

I assume that you want to store information concerning a certain person and retrieve this information using the person's name.
I would suggest to use a dictionary like so:
s = 'reset the password for johnny.mnemonic'
t = 'create the password for another.guy'
u = 'tell the password for a.gal'
d = {}
d[s.split()[-1]] = s
d[t.split()[-1]] = t
d[u.split()[-1]] = u
for k, v in d.items():
print(k, '\n\t', v)

Related

How to restrict the user to input only letters and numbers in Python 3?

I need to write an algorithm that validates a player's username and checks to see if the name is registered in an external text file.
playerName = input('Please enter a player name')
How do I restrict the user to only being able to enter letters and numbers?
You cannot restrict what the user can type (at least with input) but you can use a while loop to repeat the input request until user gets it right
As #peer said, you can use a regex in a while loop.
There is no way to do it with input command.
Exemple of code:
import re
playerName = '_'
while(not re.match("^[A-Za-z0-9]*$", playerName)):
playerName = input('Please enter a player name (Only letters and numbers)')
print("PlayerName: ", playerName)
EDIT
As #Joe Ferndz wrote in comment, you can use isalnum() method to check if your playerName is alphanumeric, so you don't even need to use regex
playerName = '_'
while(not playerName.isalnum()):
playerName = input('Please enter a player name (Only letters and numbers)')
print("PlayerName: ", playerName)

Python: String similar to everything

I need to use string (or int, bool, etc.) which will be same as everything. So this code:
user_input = input()
if user_input in *magic_string_same_as_everything*:
return True
should return True everythine, no matter what will user type into console.
Thanks for your help
Edit:
I see, that I've asked verry badly.
I'm trying to get 3 user input in this for cycle:
user_input = ["", "", ""] # Name, class, difficulty
allowed_input = ["", ["mage", "hunter"], ["e", "m", "h"]]
difficulty = {"e": 1, "m": 2, "h": 3}
message = ["Please enter your heroic name",
"Choose character (mage/hunter)",
"Tell me how difficult your journey should be? (e / m / h)"]
print("Welcome to Dungeons and Pythons\n" + 31 * "_")
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if user_input[i] in allowed_input[i]:
break
Choose of name is without restrictions.
I hope, that now my question makes a sense.
You could just get rid of the if-statement and return True without the check or (if you really want to use the if-statement) you type if(True) and it will always be true.
You want True for non empty string?
Just use user_input as bool.
user_input = input()
if user_input:
return True
In your question Name is special case, just check it like this and for the rest of input you can use range(1,3).
Alternatively switch to using regular expressions
allowed_input = ["\A\S+", "\A(mage|hunter)\Z", "\A[emh]\Z"]
for i in range(3):
while True:
print(message[i], end=": ")
user_input[i] = input()
if re.match(allowed_input[i], user_input[i]) :
break
Initial response
This one liner should work.
If user inputs anything, it counts as an input & prints 'True', but if user just hits 'Enter' without typing anything, it returns 'No input'
print ("True" if input("Type something:") else 'No input')
After your edited question
To achieve what you want, you can define a function that checks for the user input values & corrects them if incorrect.
import re
# for user input, a single line of code is sufficient
# Below code takes 3 inputs from user and saves them as a list. Second and third inputs are converted to lowercase to allow case insensitivity
user_input = [str(input("Welcome to Dungeons & Pythons!\n\nPlease enter username: ")), str(input("Choose character (mage/hunter): ").lower()), str(input("Choose difficulty (e/m/h):").lower())]
print (user_input) # Optional check
def input_check(user_input):
if user_input[0] != '':
print ("Your username is: ", user_input[0])
else:
user_input[0] = str(input("No username entered, please enter a valid username: "))
if re.search('mage|hunter', user_input[1]):
print ("Your character is a : ", user_input[1])
else:
user_input[1] = str(input("Incorrect character entered, please enter a valid character (mage/hunter): ").lower())
if re.search('e|m|h',user_input[2]):
print ("You have selected difficulty level {}".format('easy' if user_input[2]=='e' else 'medium' if user_input[2]=='m' else 'hard'))
else:
user_input[2] = str(input("Incorrect difficulty level selected, please choose from 'e/m/h': "))
return (user_input)
check = input_check(user_input)
print (check) # Optional check
In each of the if-else statements, the function checks each element and if no input/ incorrect input (spelling mistakes, etc.) are found, it asks the user to correct them & finally returns the updated list.
Test Output
With correct entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username: dfhj4
Choose character (mage/hunter): mage
Choose difficulty (e/m/h):h
['dfhj4', 'mage', 'h']
Your username is: dfhj4
Your character is a : mage
You have selected difficulty level hard
['dfhj4', 'mage', 'h']
With incorrect entries
[Out]: Welcome to Dungeons & Pythons!
Please enter username:
Choose character (mage/hunter): sniper
Choose difficulty (e/m/h):d
['', 'sniper', 'd']
No username entered, please enter a valid username: fhk3
Incorrect character entered, please enter a valid character (mage/hunter): Hunter
Incorrect difficulty level selected, please choose from 'e/m/h': m
['fhk3', 'hunter', 'm']

Adding and checking values within a list of tuples

So i am trying to make a menu that will present the user with a function based on their choice, the purpose of the one below is to add words and the description of that word in a list of tuples (criteria of schoolwork) but i feel like i have hit a wall with what i currently have.
##Lägger in nya ord i ordboken
def menu2_val1(lista):
lista_ord = input("Input word ")
##Looping trough the list to look for duplicate words
for dup in lista[0]:
if dup in lista_ord:
print("The word already exists")
return menu2()
else:
lista_definition = input("Input definition ")
lista_ord = (lista_ord, lista_definition)
ny_lista = list(lista)
ny_lista.append(lista_ord)
lista = tuple(ny_lista)
If the word already exists in the list it should inform the user and go back to the menu
def menu2():
programm = 1
lista = [("word", "description")]
while programm > 0:
print("""
1.Insert
2.Lookup
3.Delete Word
4.Exit program
""")
menu2=input("(Tupel Meny)What would you like to do? ")
## Calls on functions based on input
if menu2=="1":
menu2_val1(lista)
elif menu2=="2":
menu2_val2(lista)
elif menu2=="3":
menu2_val3(lista)
Your code has the line for dup in lista[0]:, which will only loop through the first element of lista instead of the whole list.
Try out for dup in lista: instead and see if that helps.
Just for closure i did manage to solve it in the end with the following code
def menu2_val1(lista):
lista_ord = input("Input Word ")
dup = [x[0] for x in lista]
## Storing the first value of each in tuple in dup
if lista_ord in dup:
## Looks for the new word in dup
print("The word already exists")
return
else:
lista_definition = input("Input definition ")
nytt_ord = lista_ord, lista_definition
lista.append (nytt_ord)
Potato's suggestion would end up comparing string values to tuple values which wouldn't work

newbie python - adding 'cilent' into the txt file

I'm working on a registration in my school project, and one part of it is about registartion. I have to input client in form of
username
password
name
lastname
role
so he can be registered and appended into the txt file,
but i also have to make "username" be the unique in file (because I will have the other cilents too) and "password" to be longer than 6 characters and to possess at least one number.
Btw role means that he is a buyer. The bolded part I didn't do and I need a help if possible. thanks
def reg()
f = open("svi.txt","a")
username = input("Username: ")
password = input("Password: ")
name = input("Name of a client: ")
lastname = input("Lastname of a client: ")
print()
print("Successful registration! ")
print()
cilent = username + "|" + password + "|" + name + "|" + lastname + "|" + "buyer"
print(cilent,file = f)
f.close()
You need to add some file parsing and logic in order to accomplish this. Your jobs are to:
1: Search the existing file to see if the username exists already. With the formatting as you've given it, you need to search each line up to the first '|' and see if the new user is uniquely named:
name_is_unique = True
for line in f:
line_pieces = line.split("|")
test_username = line_pieces[0]
if test_username == username:
name_is_unique = False
print("Username already exists")
break
2: See if password meets criteria:
numbers=["0","1","2","3","4","5","6","7","8","9"]
password_contains_number = any(x in password for x in numbers)
password_is_long_enough = len(password) > 6
3: Write the new line only if the username is unique AND the password meets your criteria:
if name_is_unique and password_contains_number and password_is_long_enough:
print(cilent,file = f)
Edit: You may also have to open it in reading and writing mode, something like "a+" instead of "a".

Creating a autocorrect and word suggestion program in python

def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
while (user_input == ""):
user_input = input("key in word you wish to enter: ")
user_word = autocorrect(user_input).replace(' ', '')
with open('big.txt') as myFile:
for word in myFile:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
Basically when I had a dictionary of correctly spelled word in "big.txt", if I get the similar from the user input and the dictionary, I will print out a line
I am comparing between two string, after I sort it out
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
When I try hard code with other string like
if ("a" == "a"):
print("The word",user_input,"exist in the dictionary")
it worked. What wrong with my code? How can I compared two string from the file?
What does this mean? Does it throw an exception? Then if so, post that...
However I am not able to execute the line
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
because I can run a version of your program and the results are as expected.
def autocorrect(word):
Break_Word = sorted(word)
Sorted_Word = ''.join(Break_Word)
return Sorted_Word
user_input = ""
#while (user_input == ""):
user_input = raw_input("key in word you wish to enter: ").lower()
user_word = autocorrect(user_input).replace(' ', '')
print ("user word '{0}'".format(user_word))
for word in ["mike", "matt", "bob", "philanderer"]:
NewWord = str(word.replace(' ', ''))
Break_Word2 = sorted(NewWord.lower())
Sorted_Word2 = ''.join(Break_Word2)
if (Sorted_Word2 == user_word):
print("The word",user_input,"exist in the dictionary")
key in word you wish to enter: druge
user word 'degru'
The word druge doesn't exist in the dictionary
key in word you wish to enter: Mike
user word 'eikm'
('The word','mike', 'exist in the dictionary')
Moreover I don't know what all this "autocorrect" stuff is doing. All you appear to need to do is search a list of words for an instance of your search word. The "sorting" the characters inside the search word achieves nothing.

Resources