This question already has answers here:
How can I print multiple things (fixed text and/or variable values) on the same line, all at once?
(13 answers)
Closed 9 months ago.
So for my first project it is a simple program that prints your name class you are in and what high school you went to. The one thing that is messing me up is for one of them I have to use one print() statement for all this and I need to format it so that each piece of information is on a different line.
What I want for the format:
first_name, last_name
course_id, course_name, email
school
But what I get is
first_name, last_name
course_id, course_name, email
school
How do I remove the space?
My code is as follows:
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print inserts a space between each argument. You can disable this by adding , sep='' after the last '\n', but then there won't be any spaces between first_name and last_name or between course_id and course_name, etc. You could then go on to insert , ' ' manually where you need it in the print statement, but by that point it might be simpler to just give print a single argument formed by concatenating the strings together with explicit spaces:
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name
+ ' ' email + '\n' + school + '\n')
As mentioned here, you can use the sep='' argument to the print() function. That will let you set the separator between printed values (which is a space by default) to whatever you want, including an empty string. You'll have to remember to add spaces between the values that you do want separated. E.g.,
print(first_name, ' ', last_name, '\n', course_id, [...], sep='')
There's a better way to do this, involving the format() method on strings, but your professor is probably saving that one for the next lesson so I won't cover it in detail now. Follow the link to the Python docs, and read the section on Format String Syntax, if you want more details. I'll just show you an example of what your code would look like using format():
print("{} {}\n{} {} {}\n{}".format(first_name, last_name, course_id, course_name, email, school))
Note no \n at the end, since print() automatically adds a newline unless you tell it otherwise.
I recommend reading through str.format() to print your information.
The spaces in your output come from the fact that you've called the print function, passing a list of strings, instead of passing the print function a single string.
print(first_name + ' ' + last_name + '\n' + course_id + ' ' + course_name + ' ' + email + '\n' + school)
yields
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Just don't add space in your code
print(first_name, last_name, '\n',course_id, course_name, email, '\n', school, '\n')
There are a number of ways to do so.
First can be str.format() as
print ('{} {}\n{} {} {}\n{}'.format(first_name, last_name, course_id, course_name, email, school))
Second can be
print (first_name, ' ', last_name, '\n',course_id, ' ', course_name, ' ', email, '\n',school, sep = '')
And the third can be
print (first_name + ' ' + last_name + '\n' + str(course_id) + ' ' + course_name + ' ' + email + '\n' + school)
Simple multiline print in python using f-string,
first_name = 'Daniel'
last_name = 'Rust'
course_id = 'Csci 160'
course_name = 'Computer Science 160'
email = 'blah#gmail.com'
school= 'Red River Highschool'
#variables printed for B
print(first_name, last_name, '\n', course_id, course_name, email, '\n', school, '\n')
print(f'''
{first_name}, {last_name}
{course_id}, {course_name}, {email}
{school}''')
Daniel Rust
Csci 160 Computer Science 160 blah#gmail.com
Red River Highschool
Daniel, Rust
Csci 160, Computer Science 160, blah#gmail.com
Red River Highschool
[Program finished]
How to print several lines by using one print statement and how to add new line?
pi = 3.14159 # approximate
diameter = 3
radius = diameter/2
area = pi * radius * radius
circumference = 2 * pi * radius
print("{}\n{}\n{}\n".format(area,radius,circumference))
output::
7.068577499999999
1.5
9.424769999999999
the above you will get corrcet answer for this code.
Related
I'm trying to get through my first semester of Python and am struggling. My dictionary is correct however, I cannot get what I want. I need the user to input a patient ID and then the program will display the ID with the name linked to it in the dictionary as the name is the value. Then if the user enters an ID that is not in the dictionary the computer tells them so. If they enter done the program says DONE! When numbers are entered the program needs to continue asking the question until done is typed. Here is was I have so far:
patientinfo = {}
lines = open('PatientsNames.txt')
lines.readline()
for line in lines:
id=line[:8]
if id not in patientinfo:
endlastname = line.find(' ', 8)
lastname = line[8:endlastname]
firstname = line[endlastname+1:]
patientinfo[id] = lastname + ', ' + firstname
answer = raw_input("Enter an ID ('done' to exit)")
try:
if answer in patientinfo.keys():
print answer, patientinfo(val)
except:
if answer not in patientinfo.keys():
print 'No patient with that ID'
else:
if answer='done':
print 'DONE!'
I'm super new to Python and just trying my hand at a random email generator.
I'm just using json files with datasets in them, so there may be a better way to do this.
I can get the script to work no problems, but I need some advice on something. I want the senders email to be the same as the sign off name.
I.E. david_jones#hotmail etc comes from Regards, David Jones. At the moment i've got it generating a separate random email, and separate sign off name. I need to link the two. Everything else is ok at the moment.
Can anyone help me with a better way to do this?
Code:
import json
import random
f = open("C:/Users/*/Desktop/Email.txt", "a")
sentfrom = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Send.json').read())
send = sentfrom [random.randint(0,4)]
carboncopy = "CC:"
receiver = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/To.json').read())
to = receiver[random.randint(0,4)]
datesent = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Date.json').read())
date = datesent[random.randint(0,4)]
subjects = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Subject.json').read())
subject = subjects[random.randint(0,4)]
greetings = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Greeting.json').read())
greeting= greetings[random.randint(0,4)]
firstsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent1.json').read())
sent1 = firstsentence[random.randint(0,4)]
secondsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent2.json').read())
sent2 = secondsentence[random.randint(0,4)]
thirdsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent3.json').read())
sent3 = thirdsentence[random.randint(0,4)]
fourthsentence = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sent4.json').read())
sent4 = fourthsentence[random.randint(0,4)]
farewell = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Goodbye.json').read())
goodbye = farewell[random.randint(0,4)]
regards = json.loads(open('C:/Users/*/Desktop/*/Scripts/Test/Sender.json').read())
salutation = regards[random.randint(0,4)]
conversation = send +'\n'+ to +'\n'+ carboncopy +'\n'+ date +'\n'+ subject +'\n'+ '\n' + greeting +', \n'+ '\n' + sent1 +'\n'+ '\n' + sent2 +'\n'+'\n'+ sent3 +'\n'+'\n'+ sent4 +'\n'+'\n'+ goodbye +'\n'+'\n'+ salutation
f.write(conversation)
f.close()
Thanks in advance,
Buzz
Assuming that regards is what contains the sign off name..
You want to first get rid of the sign off name, instead of 'Regards, John Doe', Have all of them be 'Regards', 'Best', 'Thanks!' etc. maybe just create a list instead of reading it from json:
regards = ['Regards,', 'Best,', 'Thanks!' ...]
Assuming everyone's format in email is the same, i.e. john_doe#whatever.com, you can get the name from this:
my_name = to.split('#')[0].replace('_', ' ').title()
# my_name will be 'John Doe'
And then add my_name to the conversation after salutation.
I have this problem,I have a field that filter the messages when you click on Send message on the social network, but my problem is that i have to refresh the page to get the data. I wanna get it at the same time I send the message.
#api.multi
#api.depends('message_ids')
def _compute_defect_summary_attachment_ids(self):
body = ' '
attachments = []
cont = 1
for rec in self:
for msj in rec.message_ids:
if msj.message_type == 'comment' and msj.subtype_id.name == 'Debates':
soup = BeautifulSoup(msj.body)
body += u'- Observación ' + str(cont) + ': ' + soup.text + '\n' \
+ '- Reportante: ' + msj.create_uid.name + '\n' \
+ '- Fecha: ' + msj.date + '\n\n'
cont += 1
rec.update({
'defect_summary': body})
Trying fixing it, I saw when I add the widget doesn't work. Any idea? I need to use the also the widget.
odoo 10 : Inherit mail.thread object in your class and also you can add message_ids in view.you can use in any module or class.
1) models/custom.py
class CustomDetails(models.Model):
_name = 'custom.details'
_inherit = ['mail.thread', 'ir.needaction_mixin']
2) views/custom_view.xml
<field name="message_ids" widget="mail_thread"/>
I'd like to split a string with delimiters which are in a list.
The string has this pattern: Firstname, Lastname Email
The list of delimiters has this: [', ',' '] taken out of the pattern.
I'd like to split the string to get a list like this
['Firstname', 'Lastname', 'Email']
For a better understanding of my problem, this is what I'm trying to achieve:
The user shall be able to provide a source pattern: %Fn%, %Ln% %Mail% of data to be imported
and a target pattern how the data shall be displayed:
%Ln%%Fn%; %Ln%, %Fn; %Mail%
This is my attempt:
data = "Firstname, Lastname Email"
for delimiter in source_pattern_delimiter:
prog = re.compile(delimiter)
data_tuple = prog.split(data)
How do I 'merge' the data_tuple list(s)?
import re
re.split(re.compile("|".join([", ", " "])), "Firstname, Lastname Email")
hope it helps
Seems you want something like this,
>> s = "Firstname, Lastname Email"
>>> delim = [', ',' ']
>>> re.split(r'(?:' + '|'.join(delim) + r')', s)
['Firstname', 'Lastname', 'Email']
A solution without regexes and if you want to apply a particular delimiter at a particular position:
def split(s, delimiters):
for d in delimiters:
item, s = s.split(d, 1)
yield item
else:
yield s
>>> list(split("Firstname, Lastname Email", [", ", " "]))
["Firstname", "Lastname", "Email"]
What about splitting on spaces, then removing any trailing commas?
>>> data = "Firstname, Lastname Email"
>>> [s.rstrip(',') for s in data.split(' ')]
['Firstname', 'Lastname', 'Email']
You are asking for a template based way to reconstruct the split data. The following script could give you an idea how to progress. It first splits the data into the three parts and assigns each to a dictionary entry. This can then be used to give a target pattern:
import re
data = "Firstname, Lastname Email"
# Find a list of entries and display them
entries = re.findall("(\w+)", data)
print entries
# Convert the entries into a dictionary
dEntries = {"Fn": entries[0], "Ln": entries[1], "Mail": entries[2]}
# Use dictionary-based string formatting to provide a template system
print "%(Ln)s%(Fn)s; %(Ln)s, %(Fn)s; %(Mail)s" % dEntries
This displays the following:
['Firstname', 'Lastname', 'Email']
LastnameFirstname; Lastname, Firstname; Email
If you really need to use the exact template system you have provided then the following could be done to first convert your target pattern into one suitable for use with Python's dictionary system:
def display_with_template(data, target_pattern):
entries = re.findall("(\w+)", data)
dEntries = {"Fn": entries[0], "Ln": entries[1], "Mail": entries[2]}
for item in ["Fn", "Ln", "Mail"]:
target_pattern= target_pattern.replace("%%%s%%" % item, "%%(%s)s" % item)
return target_pattern % dEntries
print display_with_template("Firstname, Lastname Email", r"%Ln%%Fn%; %Ln%, %Fn%; %Mail%")
Which would display the same result, but uses a custom target pattern:
LastnameFirstname; Lastname, Firstname; Email
Just studying data structures in python for a project and can't work out the difference in a dictionary and a data structures in this form:
class Address:
def __init__(self, house_number, house_street, house_city,
house_county, house_postcode):
self.number = house_number
self.street = house_street
self.city = house_city
self.county = house_county
self.postcode = house_postcode
def __repr__(self):
return ('<Class: \'Address\', '+ str(self.number) + ' ' +
self.street + ' ' + self.city + ' ' +
self.county + ' ' + self.postcode + '>')
## Creates an object Address and assign it to a variable
my_address = Address(1, 'abc', 'def', 'ghi', 'jkl')
## Print the object My_address
print 'Address object:', my_address
print 'house number:', my_address.number
## change house number
my_address.number = 555
print 'NEW house number:', my_address.number
The code sample is modified from sample code given in a lecture at university of york.
A python dict is a highly optimized hash table, which is a data structure.
So, to put it differently, a python dict is one example of a data structure. So are the set, list, string and unicode types. A custom class is again another data structure, one that is highly customizable to your application needs.
From the WikiPedia entry on Data structure:
In computer science, a data structure is a particular way of storing and organizing data in a computer so that it can be used efficiently.
Data structures in python can have the form of lists,dictionaries,even for emtpy classes that just use the pass keyword.They are like the struct in C.
They are those objects that can actually store some data in some order or not.