Python Forum
Replacing a few characters of a specified character but not all of them from a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replacing a few characters of a specified character but not all of them from a string
#1
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 :)
Reply
#2
(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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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()
Reply
#4
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.
Reply
#5
Format in which username and password is stored in a .txt file

['username', 'password']
Reply
#6
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
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#7
(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
Reply
#8
(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
:)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help with extracting characters from string valentino1337 2 329 Feb-19-2024, 01:17 PM
Last Post: Pedroski55
  Split string into 160-character chunks while adding text to each part iambobbiekings 9 9,491 Jan-27-2021, 08:15 AM
Last Post: iambobbiekings
  Change each character of list into an different characters Angry_bird89 1 2,022 Jun-19-2020, 08:29 AM
Last Post: Angry_bird89
  Counting the number of occurrences of characters in a string nsadams87xx 1 1,880 Jun-16-2020, 07:22 PM
Last Post: bowlofred
  Tab character in a string prints 8 spaces hecresper 6 20,307 Aug-27-2019, 02:38 PM
Last Post: snippsat
  Print strings enclosed with a character with different characters aylmaoxd 1 1,874 Aug-17-2019, 03:35 PM
Last Post: Resistance
  Finding and storing all string with character A at middle position Pippi 2 2,649 Jan-20-2019, 08:23 AM
Last Post: Pippi
  testing indivudual string for alternating characters Titus444 3 2,611 Nov-01-2018, 10:28 PM
Last Post: j.crater
  Unexpected character after line continuation character joshyb123 5 10,561 Sep-05-2018, 08:08 AM
Last Post: perfringo
  unexpected character after line continuation character error newbie 10 14,491 Aug-09-2018, 06:07 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020