Python printing format using """ """ format - python

I am writing an email application to send mass emails. In the body of the email I want to insert the first name from a list of names. But I can't seem to figure out why this code isn't working. Any suggestions are most appreciated.
first_name = " "
body = """\
Dear {},
Here is new email.
Thanks.
Mike """.format(first_name)
def send_test_email(body):
first_name = 'mike'
print(body)
send_test_email(body)
Output:
Dear ,
Here is new email.
Thanks.
Mike

You have already assigned what body is. So even if you change value of parameter (first_name) in format later, it does not affect the original body.
first_name = " "
body = """\
Dear {},
Here is new email.
Thanks.
Mike """
def send_test_email(body):
first_name = 'mike'
print(body.format(first_name))
send_test_email(body)
# Dear mike,
# Here is new email.
# Thanks.
# Mike

Related

Find a money amount specified in a email and print it next to a str

I've been trying to make an API that automates a detector for new transaction emails in my Gmail Account, and now it detects all the emails coming from my bank that are related to a transaction send to myself, but it prints the whole email (which contains the money expressed like this "$" in a certain point of the email), and I want it that the script detects the money amount and then prints a string with it like this for example
print("Transaction Recieved"," $" ,moneyAmount,"!")
The Messages Filter part of the script
#Messages Filter
message_count = 50
for message in messages[:message_count]:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
email = (msg['snippet'])
if "Datos de la transferencia que recibiste Monto $" in email:
service.users().messages().modify(userId='me', id=message['id'], body={'removeLabelIds': ['UNREAD']}).execute()
print(f'{email}\n')
And I can't figure how to make it so it detects the money amount that is expressed inside the bank's email.
I tried to do an attempt of making it to detect a string pattern of a value of 1 digit that could go from 1 to 9 followed by a "." and after that a value of 3 digits that could go from 001 to 999 and then print the whole value, but it didn't work so I'm out of ideas.
Here's my attempt of making it
#Messages Filter
message_count = 50
for message in messages[:message_count]:
msg = service.users().messages().get(userId='me', id=message['id']).execute()
email = (msg['snippet'])
if "Datos de la transferencia que recibiste Monto $" in email:
value = re.findall(r'$\d{1}.\d{3}', email)
service.users().messages().modify(userId='me', id=message['id'], body={'removeLabelIds': ['UNREAD']}).execute()
print(f'{email}\n')
print(f'{value}\n')
The amount of money is displayed like this in the email
And this is like directly from the email
If someone with an idea could help me, I would be very grateful.
P.S.:Btw if you see something that you don't understand because of the language, it's because it's in Spanish, but it's mostly in strings so it shouldn't be a problem.
I had to replace the string pattern that I was using for the re and it ended like this
re.findall(r'\$\d+(?:.\d{3})+(?:,\d+)?', email)
Insted of this
re.findall(r'$\d{1}.\d{3}', email)
Thanks to #Grismar for the answer

How to split an email in Python after '#'?

I have this piece of code but when you insert an email, the domain does not print fully. Can someone please explain what is wrong with the code and if there is a faster option? (I am new to Python)
email = input ('Enter your email address: ').strip()
at = email.find ('#')
after_at = email.find (' ' , at)
host = email [at+1 : after_at]
print (host)
Ex. abc#gmail.com > gmail.co
You should be able to use str.split:
domain = email.split('#')[-1]

How to alter user input?

So atm I'm making a table in python, and for it, I need the user to supply a name of a person for the table (e.g. David Beckham). However when the user has entered this and the table appears, the name needs to look like this: Beckham, David. How would I go about doing this?
With Python 3.6+ you can use formatted string literals (PEP 498). You can use str.rsplit with maxsplit=1 to account for middle names:
x = 'David Robert Bekham'
first_names, last_name = x.rsplit(maxsplit=1)
res = f'{last_name}, {first_names}'
# 'Bekham, David Robert'
Just store the input in a variable:
name = input()
first_name, last_name = name.split(" ")
table_value = last_name + ", " + first_name

Find a way to add a string to a tuple

y="Peter Email: peter#rp.com Phone: 91291212"
z="Alan Email: alan#rp.com Phone: 98884444"
w="John Email: john#rp.com Phone: 93335555"
add_book=str(y) ,"" + str(z) ,"" + str(w)
**I am trying to add a contact into my address book but I am not sure how to add the string "details" into the add_book. I also found that I cannot use append because its a tuple.
details = raw_input("Enter name in the following format: name Email: Phone:")
print "New contact added"
print details
if details in add_book:
o=add_book+details
print "contact found"
print details
print add_book
address_book = {}
address_book['Alan'] = ['alan#rp.com, 91234567']#this is what I was supposed to do:
#but when I print it out, the output I get is:
{'Alan': ['alan#rp.com, 91234567']} #but I want to remove the '' and {}
I am still an amateur in programming with python so I really need all the help I can get, thanks:)!!
A simple fix would be to use a list instead of a tuple. You can do this by changing your initialization of add_book from:
add_book=str(y) ,"" + str(z) ,"" + str(w)
to:
add_book = [y,z,w]
#No need to call str() every time because your data are already strings
However, wouldn't it make more sense to organize your data as a list of dictionaries? For example:
contacts = ["Peter", "Alan", "John"]
addr_book = [len(contacts)]
for i in range(len(contacts)):
contact = contacts[i]
email= raw_input(contact+"'s email: ")
phone= raw_input(contact+"'s phone: ")
addr_book[i] = {'name':contact, 'email':email, 'phone':phone}
FURTHERMORE:
If I understood your question correctly, you have specific requirements as to how the output of your program should look. If you use the above data format, you can create whatever output you like. for example, this code
def printContact(contact):
print contact['name']+': ['+contact[email]+','+contact[phone]+']'
will output something like:
Alan: [alan#email.com,555-555-5555]
Of course you can change it however you like.
firstly [] is a list. a tuple is (,);
so what you want is
address_book['Alan'] = ('alan#rp.com', '91234567')
But this seems quite odd. What i would do is create a class
class Contact(object):
name = "Contact Name"
email = "Contact Email"
ph_number = "00000000"
def __str__(self):
return "%S: %s, %s" % (self.name, self.email, self.ph_number)
then
address_book = []
contact_alan = Contact()
contact_alan.name = "Alan"
contact_alan.email = "alan#rp.com"
contact_alan.ph_number = "91234567"
print contact
(not next to a machine with python so it might be slightly wrong. Will test it when i can get to one.)
EDIT:- as Paul pointed out in his comment:
class Contact(object):
def __init__(self, name, email, ph_number):
self.name = name
self.email = email
self.ph_number = ph_number
contact_alan = Contact(name="Alan", email = "alan#rp.com", ph_number="91234567")

Retrieve gtalk nickname in python xmpp

In python xmpp module, I'm able to retrieve the nickname of any contacts as follows:
self.connection.auth(userJid.getNode(), self.password)
self.roster = self.connection.getRoster()
name = self.roster.getName(buddyJid)
..where buddyJid is of the form user#gmail.com.
Now, I need to retrieve the nickname of the user who authenticates the connection (userJid). I cannot find the name using the above method.
Which method can I use retrieve the name of the current user?
This information is not in the roster. You will need to query the clients individually and get their vCard by sending this IQ :
<iq from='stpeter#jabber.org/roundabout'
id='v1'
type='get'>
<vCard xmlns='vcard-temp'/>
</iq>
Thank you nicholas_o, this is a sample function I put together based your suggestion. (The XML logic isn't ideal, but it was sufficient for the simple task I needed this for)
def vcard(disp, jid):
msg = xmpp.protocol.Iq()
msg.setType('get')
msg.setTo(jid)
qc = msg.addChild('vCard')
qc.setAttr('xmlns', 'vcard-temp')
rep = disp.SendAndWaitForResponse(msg)
# to see what other fields are available in the XML output:
# print rep
userid=fname=lname=title=department=region=None
for i in rep.getChildren():
for j in i.getChildren():
if j.getName() == "TITLE":
title = j.getData().encode('utf-8')
for k in j.getChildren():
if k.getName() == "GIVEN":
fname = k.getData().encode('utf-8')
if k.getName() == "FAMILY":
lname = k.getData().encode('utf-8')
if k.getName() == "ORGUNIT":
department = k.getData().encode('utf-8')
if k.getName() == "REGION":
region = k.getData().encode('utf-8')
return fname, lname, title, department, region

Categories

Resources