I am new to learning how to use string interpolation in strings and am having trouble getting this example I am working with to actual print the right results.
I've tried to do:
print "My name is {name} and my email is {email}".format(dict(name="Jeff", email="me#mail.com"))
And it errors saying KeyError: 'name'
Then I tried using:
print "My name is {0} and my email is {0}".format(dict(name="Jeff", email="me#mail.com"))
And it prints
My name is {'email': 'me#mail.com', 'name': 'Jeff'} and my email is {'email': 'me#mail.com', 'name': 'Jeff'}
So then I tried to do:
print "My name is {0} and my email is {1}".format(dict(name="Jeff", email="me#mail.com"))
And it errors saying IndexError: tuple index out of range
It should give me the following output result back:
My name is Jeff and my email is me#mail.com
Thanks.
Just remove the call to dict:
>>> print "My name is {name} and my email is {email}".format(name="Jeff", email="me#mail.com")
My name is Jeff and my email is me#mail.com
>>>
Here is a reference on the syntax for string formatting.
You're missing the [] (getitem) operator.
>>> print "My name is {0[name]} and my email is {0[email]}".format(dict(name="Jeff", email="me#mail.com"))
My name is Jeff and my email is me#mail.com
Or use it without calling dict
>>> print "My name is {name} and my email is {email}".format(name='Jeff', email='me#mail.com')
My name is Jeff and my email is me#mail.com
Related
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]
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
I a have a SQLite Database with:
first_name email password
Andrew t#t.com abcde
I am using this to check if there is a matching email and password:
if User.userManager.filter(email = postData['email'], password =
postData['password']):
name = User.userManager.filter(email = postData['email'], password = postData['password'])
print name.get('first_name')
return "success"
When I try to print first_name from the query i did above I get error 'too many values to unpack'
This is happening because get() method expecting for keyword arguments:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#get
The QuerySet returned by filter() method could contain more than one entry:
https://docs.djangoproject.com/en/1.11/ref/models/querysets/#filter
, so you should specify expected value for the requested field.
One of the ways to access this value is:
print name.get(first_name='Andrew').first_name
On the other hand, you could limit your filter query:
User.userManager.filter(email = postData['email'], password = postData['password'])[:1]
Or just use get() method straightway and access field value directly:
user = User.userManager.get(email = postData['email'], password = postData['password'])
print user.first_name
I'm trying to write a code that iterates through a txt file and only gets the lines I want to print them out.
the text file should look like so:
mimi
passwordmimi
mimi johnson
somejob
joji
passwordjoji
jojo
somejob
john
passwordjohn
jonathan
somejob
....
and so on. this text file contains basically a user information (for a log in). I need to make everyone's username print out and their real name (ex: mimi and mimi johnson.) and only those. I don't want the current user's info to print out (in this ex: joji)
here is my code:
username="joji"
file=open("username.txt","r")
x=file.readlines()
x=[item.rstrip('\n') for item in x]
x=iter(x)
for line in x:
if line==username:
next(x,None)
next(x,None)
next(x,None)
else:
print line + " username" ****username should print out. ex:mimi or john
next(x,None)
print line +" real name ****real name should print out. ex: mimi johnson or jonathan
for whatever reason when I run this program and i print out the second **** i put, it prints out the username's twice. (so ex:
mimi username
mimi real name
mimi johnson username
mimi johnson real name
john username
john real name
jonathan username
jonathan real name
....
why is that? it should print out
mimi username
mimi johnson real name
john username
jonathan realname
...
if someone could help me out i'd be really grateful i dont get python.
Im also open to any other suggestions to do this.
EDIT::: i tried making a change with a suggestion this is the outcome:
new block of code:
else:
print line + "username"
line =next(x,None)
print line
this is the new outcome:
mimi username
passmimi real name
mimi johnson username
somejob real name
john username
passjohn real name
jonathan username
somejob real name(***im assuming this one is from john's job)
:/ its not doing what its supposed to
I would recommend using regex to parse this file:
import re
# regex expression to parse the file as you provided it
# you could access the parseddata as a dict using the
# keys "username", "password", "real_name" and "job"
ex = "\n*(?P<username>.+)\n(?P<password>.+)\n(?P<real_name>.+)\n(?P<job>.+)[\n\$]"
with open("usernames.txt", 'r') as users:
matches = re.finditer(ex, users.read())
for match in matches:
user = match.groupdict() # user is a dict
# print username and real name
print(user['username'], "username", user['real_name'], "real name")
Edit: I figured that regex was not really needed here as the format of this file is quite simple. So here is the same thing without using regex.
def parse(usersfile):
# strip line break characters
lines = (line.rstrip('\n') for line in usersfile)
# keys to be used in the dictionnary
keys = ('username', 'password', 'real_name', 'job')
while True:
# build the user dictionnary with the keys above
user = {key: line for key, line in zip(keys, lines)}
# yield user if all the keys are in the dict
if len(user) == len(keys):
yield user
else: # stop the loop
break
with open("usernames.txt", 'r') as usersfile:
for user in parse(usersfile):
# print username and real name
print(user['username'], "username", user['real_name'], "real name")
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")