Undesirable line break mysteriously appearing in a print() invocation - python

I'm printing some variables, like this:
print("First name:", first_name)
print("Last name:", last_name)
print("Password:", password)
The first two are displayed just fine but the last one is like this:
Password:
<the password>
Which is undesirable and inconsistent with the other ones, which is why I want it to look like this:
Password:<the password>
Using end="" did not help.

Try to convert the password into string inside the print func
print("password:",str(password))

Your password variable contains a linebreak (or its string representation does).
Either of these formatting methods will print a string variable inline with no linebreak:
>>> password = "blarf"
>>> print("password:", password)
password: blarf
>>> print(f"password: {password}")
password: blarf
If the variable contains a linebreak, though, you'll get a linebreak in the output:
>>> password = "\nblarf"
>>> print("password:", password)
password:
blarf

Try:
print("password:",password.strip())
Your password variable content likely has a linebreak before it. strip gets rid of that. Note that it also removes all whitespaces before and after the string characters in password, including before and after spaces. If you wish to only remove linebreaks from before and after, use:
print("password:",password.strip("\n"))

Try and remove any newline char that exist in the password string.
You can do so using the following:
first_name = "david"
last_name = "s"
password = "\n1234"
print("firstname:",first_name)
print("lastname:",last_name)
print("password:",password)
# firstname: david
# lastname: s
# password:
# 1234
# removing the new line
password = password.replace("\n","")
print("firstname:",first_name)
print("lastname:",last_name)
print("password:",password)
# firstname: david
# lastname: s
# password: 1234
import re
re.sub("\n", "", password)
print("firstname:",first_name)
print("lastname:",last_name)
print("password:",password)
# firstname: david
# lastname: s
# password: 1234
The first option is using replace method of string object which you can read about in the following link:
https://www.tutorialspoint.com/python/string_replace.htm
The second option is using sub of the re module which you can read about in the following link:
https://note.nkmk.me/en/python-str-replace-translate-re-sub/

Managed to resolve the problem thanks to Samwise I used :
password.splitlines()
password = password[1]
print("password:",password)
David S method works fine too
password = password.replace("\n","")
print("password:",password)

Related

How to place input function in center of page?

I want the user to be able to input their username beside the "username: " at the center but the results always be:
username: example
The "username: " is center which is what I want but the input text "example" is always not beside the "username:"
My code is below:
username = input("Username: ".center(165))
My desired outcome is:
username: example
with it being in the center of the page.
By doing input("Username: ".center(165)) you create a string of length 165 where "Username: " is placed right at the middle. So you get many spaces to the right of that string.
You want the "Username: " string to be at the right-end of the full string, so you should use rjust instead:
username = input("Username: ".rjust(165//2))

How to make a Python program automatically prints what matched after iterating through lists

I have this Python code:
with open('save.data') as fp:
save_data = dict([line.split(' = ') for line in fp.read().splitlines()])
with open('brute.txt') as fp:
brute = fp.read().splitlines()
for username, password in save_data.items():
if username in brute:
break
else:
print("didn't find the username")
Here is a quick explanation; the save.data is a file that contains variables of Batch-file game (such as username, hp etc...) and brute.txt is a file that contains "random" strings (like what seen in wordlists used for brute-force).
save.data:
username1 = PlayerName
password1 = PlayerPass
hp = 100
As i said before, it's a Batch-file game so, no need to quote strings
brute.txt:
username
usrnm
username1
password
password1
health
hp
So, let's assume that the Python file is a "game hacker" that "brute" a Batch-file's game save file in hope of finding matches and when it does find, it retrieves them and display them to the user.
## We did all the previous code
...
>>> print(save_data["username1"])
PlayerName
Success! we retrieved the variables! But I want to make the program capable of displaying the variables it self (because I knew that "username1" was the match, that's why I chose to print it). What I mean is, I want to make the program print the variables that matched. E.g: If instead of "username1" in save.data there was "usrnm", it will surely get recognized after the "bruting" process because it's already in brute.txt. So, how to make the program print what matched? because I don't know if it's "username" or "username1" etc... The program does :p (of course without opening save.data) And of course that doesn't mean the program will search only for the username, it's a game and there should be other variables like gold/coins, hp etc... If you didn't understand something, kindly comment it and I will clear it up, and thanks for your time!
Use a dict such as this:
with open('brute.txt', 'r') as f:
# First get all the brute file stuff
lookup_dic = {word.strip(): None for word in f.readlines()}
with open('save.data', 'r') as f:
# Update that dict with the stuff from the save.data
lines = (line.strip().split(' = ') for line in f.readlines())
for lookup, val in lines:
if lookup in lookup_dic:
print(f"{lookup} matched and its value is {val}")
lookup_dic[lookup] = val
# Now you have a complete lookup table.
print(lookup_dic)
print(lookup_dic['hp'])
Output:
username1 matched and its value is PlayerName
password1 matched and its value is PlayerPass
hp matched and its value is 100
{'username': None, 'usrnm': None, 'username1': 'PlayerName', 'password': None, 'password1': 'PlayerPass','health': None, 'hp': '100'}
100

How to call and iterate through specific indexes of a dictionary?

I currently have code that prints out a username and their password by means of dictionary. The output is username:abc password:12345. Right now I have them all just printing out at the same time. My main goal is to be able to email these users based on their usernames, but of course I only want to include their username and password information. Not the whole list of information. So basically I want to be able to tell the specific user only their password. For example, I would want to send an email to user abc and that email should only contain their username and password. Then I would like to send an email to user xyz but that should only contain the password of user xyz. Is there a way I can make this happen?
I currently have everything from the dictionary printing. So all the usernames and passwords are being printed out. How can I iterate through these and send an email to each user with their password?
lines = []
User_Pass = {}
#Open output file and show only lines that contain 'Success'
with open("output.txt", "r") as f:
for line in f.readlines():
#Get rid of everything in line after 'Success'
if 'Success' in line:
lines.append(line[:line.find("Success")-1])
for element in lines:
parts = element.strip().split(":")
User_Pass.update({parts[0] : parts[1]})
for key, value in User_pass.items():
print('Username: ' + key + ' Password: ' + value)
I want to be able to email each username and tell them their password. I am really not sure how to go about this. Any help would be appreciated!
Assuming you have the dictionary constructed, you just ask it for the value associated with the key, which is the username:
user_pw = User_Pass.get(username)
this will return None if the username is not in the dictionary.
Suggest you research Python dictionaries for some examples. In your loop code, you have it a little backwards as well. Anytime you want to iterate through a dictionary (the right way) you want to do it with the keys, not the items, so to loop through all in your example:
for key in User_Pass.keys():
print (key, User_Pass.get(key) )
Only fill your User_Pass dictionary when you meet "username" or "password":
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
A simple demonstration:
lines = [
"fullname:John Doe",
"username:jdoe",
"password:S3cRet",
"age:45",
]
User_Pass = {}
for element in lines:
key, value = element.strip().split(":")
if key in {"username", "password"}:
User_Pass.update({key: value})
print(User_Pass)
You get:
{'username': 'jdoe', 'password': 'S3cRet'}
Please, you should follow the naming conventions of the PEP8: "User_Pass" => "user_pass".

Searching and sorting in text files

I am fairly new to code and i have a problem in reading a text file.
For my code i need to ask the user to type in a specific name code in order to proceed to the code. However, there are various name codes the user could use and i don't know how to make it so if you type either code in, you can proceed.
For example the text file looks like this
john123,x,x,x
susan233,x,x,x
conor,x,x,x
What i need to do is accept the name tag despite what one it is and be able to print it after. All the name tags are in one column.
file = open("paintingjobs.txt","r")
details = file.readlines()
for line in details:
estimatenum = input ("Please enter the estimate number.")
if estimatenum = line.split
This is my code so far, but i do not know what to do in terms of seeing if the name tag is valid to let the user proceed.
Here is another solution, without pickle. I'm assuming that your credentials are stored one per line. If not, you need to tell me how they are separated.
name = 'John'
code = '1234'
with open('file.txt', 'r') as file:
possible_match = [line.replace(name, '') for line in file if name in line]
authenticated = False
for item in possible_match:
if code in tmp: # Or, e.g. int(code) == int(tmp)
authenticated = True
break
You can use a module called pickle. This is a Python 3.0 internal library. In Python 2.0, it is called: cPickle; everything else is the same in both.
Be warned that the way you're doing this is not a secure approach!
from pickle import dump
credentials = {
'John': 1234,
'James': 4321,
'Julie': 6789
}
dump(credentials, open("credentials.p", "wb"))
This saves a file entitled credentials.p. You can the load this as follows:
from pickle import load
credentials = load(open("credentials.p", "rb"))
print(credentials)
Here are a couple of tests:
test_name = 'John'
test_code = 1234
This will amount to:
print('Test: ', credentials[test_name] == test_code)
which displays: {'John': 1234, 'James': 4321, 'Julie': 6789}
Displays: Test: True
test_code = 2343
print('Test:', credentials[test_name] == test_code)
Displays: Test: False

How do I catch "split" exceptions in python?

I am trying to parse a list of email addresses to remove the username and '#' symbol only leaving the domain name.
Example: blahblah#gmail.com
Desired output: gmail.com
I have accomplished this with the following code:
for row in cr:
emailaddy = row[0]
(emailuser, domain) = row[0].split('#')
print domain
but my issue is when I encounter a improperly formatted email address. For example if the row contains "aaaaaaaaa" (instead of a valid email address) the program crashes with the error
(emailuser, domain) = row[0].split('#')
ValueError: need more than 1 value to unpack.
(as you would expect) Rather than check all the email addresses for their validity, I would rather just not update grab the domain and move on to the next record. How can I properly handle this error and just move on?
So for the list of:
blahblah#gmail.com
mmymymy#hotmail.com
youououou
nonononon#yahoo.com
I would like the output to be:
gmail.com
hotmail.com
yahoo.com
Thanks!
You want something like this?
try:
(emailuser, domain) = row[0].split('#')
except ValueError:
continue
You can just filter out the address which does not contain #.
>>> [mail.split('#')[1] for mail in mylist if '#' in mail]
['gmail.com', 'hotmail.com', 'yahoo.com']
>>>
What about
splitaddr = row[0].split('#')
if len(splitaddr) == 2:
domain = splitaddr[1]
else:
domain = ''
This even handles cases like aaa#bbb#ccc and makes it invalid ('').
Try this
In [28]: b = ['blahblah#gmail.com',
'mmymymy#hotmail.com',
'youououou',
'nonononon#yahoo.com']
In [29]: [x.split('#')[1] for x in b if '#' in x]
Out[29]: ['gmail.com', 'hotmail.com', 'yahoo.com']
This does what you want:
import re
l=["blahblah#gmail.com","mmymymy#hotmail.com",
"youououou","nonononon#yahoo.com","amy#bong#youso.com"]
for e in l:
if '#' in e:
l2=e.split('#')
print l2[-1]
else:
print
Output:
gmail.com
hotmail.com
yahoo.com
youso.com
It handles the case where an email might have more than one '#' and just takes the RH of that.
if '#' in row[0]:
user, domain = row[0].split('#')
print domain
Maybe the best solution is to avoid exception handling all together.
You can do this by using the builtin function partition(). It is similar to split() but does not raise ValueError when the seperator is not found. Read more: https://docs.python.org/3/library/stdtypes.html#str.partition
We can consider the string not having '#' symbol, as a simple username:
try:
(emailuser, domain) = row[0].split('#')
print "Email User" + emailuser
print "Email Domain" + domain
except ValueError:
emailuser = row[0]
print "Email User Only" + emailuser
O/P:
Email User : abc
Email Domain : gmail.com
Email User : xyz
Email Domain : gmail.com
Email User Only : usernameonly

Categories