Python Forum
Replacing a few characters of a specified character but not all of them from a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Replacing a few characters of a specified character but not all of them from a string (/thread-28982.html)



Replacing a few characters of a specified character but not all of them from a string - fatherted99 - Aug-12-2020

I am doing a school programming project, and I was starting off with some user credential authorization system
A user would input a desired password and username, the username would be compared to an external file containing other passwords and usernames and will see if the username is unique (these files will be obviously be available to one user).
When I am reading user credentials from an external file and into a list, I need to get rid of certain characters.
I know how to do this that is simple, its just for example I need to get rid of the character " ' " because extra characters are present/added on when reading from a file. If I were to replace the ' using a .replace function, wouldn't that replace all instances of ' in a username, and this is the problem - what if the username intentionally has ' within their username.

Is there a way to solve this? Basically I want to replace a character for one instance but not other instances (I was thinking converting all the characters of a username into a string, and then doing some messy math of replacing certain positions depending on lengths of list etc etc)


Sorry for being so wordy, but thanks in advance :)


RE: Replacing a few characters of a specified character but not all of them from a string - buran - Aug-12-2020

(Aug-12-2020, 05:56 PM)fatherted99 Wrote: When I am reading user credentials from an external file and into a list, I need to get rid of certain characters.
I know how to do this that is simple, its just for example I need to get rid of the character " ' " because extra characters are present/added on when reading from a file.

can you show sample input file and how you read it. this sounds like you reading the file in a incorrect way


RE: Replacing a few characters of a specified character but not all of them from a string - fatherted99 - Aug-12-2020

Hi(thanks for quick reply)

So this system is within a function and will be called when a player wants to make a NEW account
Currently is the comparison of a user input and a username from an external file which is confusing


def Create_account_function():
    
    create_account_new_USERNAME = False
   

 # I used 'r' to make the string a raw string, because sometimes pythond doesnt like a file path as a normal string, so I do this to prevent it crashing
    Create_file = open(r"A_file_path.txt", 'a')
    Create_file.write("")
    Create_file.close()

    Read_credentials = [] # this is a list to store data from an external file

    with open(r"A_file_path.txt", 'r') as PlayerCredentials_File: # open the file containing the user credentials
        for line in PlayerCredentials_File: # iterate through each line in the file
            Read_credentials.append(line.strip('\n')) # store credentials in a list

    while create_account_new_USERNAME == False: # Do until the username is unique and correct length
        
        
                    
        def user_name_check():
           
            create_account_credentials_LENGTH = False
            while create_account_credentials_LENGTH == False: # Do until the length of usernames and passwords is correct

                # User will input a username and a password which has certain character length requirements
                name = str(input("Enter a username(MUST BE AT LEAST 5 CHARACTERS LONG): "))
                password = str(input("Enter a password(MUST BE AT LEAST 8 CHARACTERS LONG): "))
            
                    
                # checks if the length of the name and password are correct and valid.
                if len(name) < 5:
                    print("Your username and/or password must be at least 5 characters for the username and 8 characters long for the password")
                elif len(password) < 8:
                    print("Your username and/or password must be at least 5 characters for the username and 8 characters long for the password")
                else:
                    print("Your username and password are at the correct length")
                    create_account_credentials_LENGTH = True # the length of usernames and passwords are now correct

            for list_length_index in range(0, len(Read_credentials)):
                
                if Read_credentials[list_length_index] == name: # if the current item in the list == the name, then the name has been already taken, so call a function to make a new username
                    print("This username has already been taken, please choose a new username (sad face)")
                    user_name_check()
                elif list_length_index + 1 == len(Read_credentials): # you have iterated through all the items in the list, meaning that the username is unique, break so we can upload details to external file.
                    print("This username has NOT been taken, this is now your username! (happy face)")
                    break
                else:
                    pass # the item did not equal the username, and we are not at the end of the list yet. Keep looping

            Player_credentials =  [name, password]
            with open(r"A_file_path.txt", 'a') as PlayerCredentials_File:
                print(Player_credentials, file=PlayerCredentials_File)  # your password is above 8 characters, your username is unique, write that to a file.
   

            


        create_account_new_USERNAME = True
        user_name_check()
         




Create_account_function()



RE: Replacing a few characters of a specified character but not all of them from a string - jefsummers - Aug-12-2020

A few things to get you started. Typically you will not create a function within a function, as you have here. You are also creating the function inside a while loop - although probably only run once, that leaves you with potentially defining the function multiple times.

You also have scope issues. Each function has its own namespace - variables within that function are visible only to things inside that function. And, the main script also has its namespace. So, the variables inside user_name_check() are not visible to Create_account_function(). Instead, you should pass the variables needed to each function and have that function return a result.

Need to fix those before you get too far into removing individual characters.


RE: Replacing a few characters of a specified character but not all of them from a string - fatherted99 - Aug-12-2020

Format in which username and password is stored in a .txt file

['username', 'password']


RE: Replacing a few characters of a specified character but not all of them from a string - buran - Aug-12-2020

split your code in chunks, that do small, but complete steps, e.g.
take user input and validate it for length
read the file content
check user input against current file content
write valid username and password to the file

at the moment you print to a file a list. that is why you get extra brackets, comma and quotes.
read how to write to a file, e.g. in following format:
username,password

given that it's a school assignment, a different format like JSON maybe more easy to handle and check against

lines 7-9 in current code are redundant. why do you have them


RE: Replacing a few characters of a specified character but not all of them from a string - Intr0spective - Aug-12-2020

(Aug-12-2020, 06:41 PM)fatherted99 Wrote: Format in which username and password is stored in a .txt file

['username', 'password']

Not sure if this will be of any help to you:

This looks like a plain ,,list,, added (appended or etc) to the .txt file - perhaps if the content(i mean values) of the list was added to the .txt file then you would not need to worry about these extra characters as is ' ?

Btw, this was practically suggested by buran, i would have deleted my post if i could since it is now redundant


RE: Replacing a few characters of a specified character but not all of them from a string - fatherted99 - Aug-13-2020

(Aug-12-2020, 06:40 PM)jefsummers Wrote: A few things to get you started. Typically you will not create a function within a function, as you have here. You are also creating the function inside a while loop - although probably only run once, that leaves you with potentially defining the function multiple times.

You also have scope issues. Each function has its own namespace - variables within that function are visible only to things inside that function. And, the main script also has its namespace. So, the variables inside user_name_check() are not visible to Create_account_function(). Instead, you should pass the variables needed to each function and have that function return a result.

Need to fix those before you get too far into removing individual characters.

Since I am not using any of the variables in the user_name_check()outside the function (it is all being executed within the function) there is not an error, however I do understand that if I were to use variables from that function outside, then it would create errors.

However as you are an experienced programmer I think you see there is a problem with how I am using functions.

"Instead, you should pass the variables needed to each function and have that function return a result" - Can you explain what you mean by this, and how I can create good practices of using functions?

(Aug-12-2020, 06:59 PM)buran Wrote: split your code in chunks, that do small, but complete steps, e.g.
take user input and validate it for length
read the file content
check user input against current file content
write valid username and password to the file

at the moment you print to a file a list. that is why you get extra brackets, comma and quotes.
read how to write to a file, e.g. in following format:
username,password

given that it's a school assignment, a different format like JSON maybe more easy to handle and check against

lines 7-9 in current code are redundant. why do you have them

Yes I agree looking at it again I do not need lines 7-9 if the file has already been previously created for me, but like if someone else were to execute this, then a file would need to be initially written as I need to read from a file straight after it, in other words reading from an empty file- please correct me if I am wrong

When you say split into chunks, do you mean create more, smaller functions?

Thanks in advance for the help

            with open(r"some file path.txt", 'a') as PlayerCredentials_File:
                print(f'{name}, {password}', file=PlayerCredentials_File)  # your password is above 8 characters, your username is unique, write that to a file.
   
Thanks for the help, writing like that works much better, no fiddly extra characters
:)