I am really stuck with this. I have to create two functions. The first one takes a string as an argument then creates and returns a tuple. The string has the following format: fisrt_name, last_name, salary. However, I must change the order to salary, first_name, last_name. Any ideas on how to do it? This is what I have so far:
def function_one(person_string):
first_name, last_name, salary=person_string.split('')
return salary, first_name, last_name
def function_two(person_tuple):
string_person = ' '.join(person_tuple)
return string_person
path_to_file = 'person.txt'
with open(path_to_file, 'r') as file
content = file.read()
print(content)
with open(path_to_file, 'r') as file:
for line in file.readlines():
tuple_person = string_to_tuple(line)
print(tuple_person)
You can try it like this
def function_one(person_string):
data = person_string.split(' ')
return (data[2], data[0], data[1])
def function_two(person_tuple):
string_person = ' '.join(person_tuple)
return string_person
Jhon = 'Jhon Smith 100000'
string = function_one(Jhon)
out = function_two(string)
print(string, out)
out:('100000', 'Jhon', 'Smith') 100000 Jhon Smith
You could just do something like this?
peoples = ["jordan lee 21", "megan bob 35",]
peoples_2 = []
for people in peoples:
first_name, last_name, salary = people.split()
peoples_2.append('{} {} {}'.format(salary, first_name, last_name))
print(peoples_2)
And if you really need it to be a tuple or list just cast it
tuple(peoples_2)
Just replace the hardcoded peoples list with the previous way you were getting the list.
Related
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
I have a requirement where in I need to convert my text files into csv and am using python for doing it. My text file looks like this ,
Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football
I want my CSV file to have the column names as Employee Name, Employee Number , Age and Hobbies and when a particular value is not present it should have a value of NA in that particular place. Any simple solutions to do this? Thanks in advance
You can do something like this:
records = """Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football"""
for record in records.split('Employee Name'):
fields = record.split('\n')
name = 'NA'
number = 'NA'
age = 'NA'
hobbies = 'NA'
for field in fields:
field_name, field_value = field.split(':')
if field_name == "": # This is employee name, since we split on it
name = field_value
if field_name == "Employee Number":
number = field_value
if field_name == "Age":
age = field_value
if field_name == "Hobbies":
hobbies = field_value
Of course, this method assumes that there is (at least) Employee Name field in every record.
Maybe this helps you get started? It's just the static output of the first employee data. You would now need to wrap this into some sort of iteration over the file. There is very very likely a more elegant solution, but this is how you would do it without a single import statement ;)
with open('test.txt', 'r') as f:
content = f.readlines()
output_line = "".join([line.split(':')[1].replace('\n',';').strip() for line in content[0:4]])
print(output_line)
I followed very simple steps for this and may not be optimal but solves the problem. Important case here I can see is there can be multiple keys ("Employee Name" etc) in single file.
Steps
Read txt file to list of lines.
convert list to dict(logic can be more improved or complex lambdas can be added here)
Simply use pandas to convert dict to csv
Below is the code,
import pandas
etxt_file = r"test.txt"
txt = open(txt_file, "r")
txt_string = txt.read()
txt_lines = txt_string.split("\n")
txt_dict = {}
for txt_line in txt_lines:
k,v = txt_line.split(":")
k = k.strip()
v = v.strip()
if txt_dict.has_key(k):
list = txt_dict.get(k)
else:
list = []
list.append(v)
txt_dict[k]=list
print pandas.DataFrame.from_dict(txt_dict, orient="index")
Output:
0 1
Employee Number 12345 123456
Age 45 None
Employee Name XXXXX xxx
Hobbies Tennis Football
I hope this helps.
I am a newbie to Python. I need to create a simple student class which includes first name, last name, id, and a dictionary which maps course name to its grade.
class Student:
def __init__(self, firstName, lastName, id, _____ (dictionary values)):
self._firstName = firstName;
self._lastName = lastName;
self._id = id;
self.
My question is how can I initizalize the dictionary values inside the constructor?
For example, let`s say I would like to add 3 course to grade mappings:
"math: 100"
"bio: 90"
"history: 80"
For example:
student1 = Student("Edward", "Gates", "0456789", math: 100, bio: 90, history: 80)
The last 3 values should go into the dictionary.
Since the number of key-value which can be part of the dictionary can vary, what should I write in the constructor parameter signature?
I want to send all the student values when I call the constructor...
If you are looking to add a dictionary Mathias' answer suffices with the key word arguments in python.
However, if you wish to add object variables from the key word arguments, you require setattr
For example, if you want something like this:
student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
print student1.math #prints 100
print student1.bio #prints 90
Then this will do the trick:
class Student(object):
def __init__(self, first_name, last_name, id, **kwargs):
self.first_name = first_name
self.last_name = last_name
self.id = id
for key, value in kwargs.iteritems():
setattr(self, key, value)
student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
Note that **kwargs will unpack only something like dictionary or tuple of tuples. If you wish to send a list of values without keys, you should use *args. Check here to know more.
Python collects all keyword arguments for you.
class Student:
def __init__(self, firstName, lastName, id, **kwargs):
self._firstName = firstName;
self._lastName = lastName;
self._id = id;
self. _grades = kwargs
Here is an excellent explanation about kwargs in python
Why not send the complete grades dictionary to the your class and store it in a variable.
(Also please note that in Python there is no semicolon at the end of the line)
class Student:
def __init__(self, firstName, lastName, id, grade_dict):
self._firstName = firstName
self._lastName = lastName
self._id = id
self._grades = grade_dict
def get_grades(self):
return self._grades
and then when you want to initialize and use the grades:
student1 = Student("Edward", "Gates", "0456789", {'math': 100, 'bio': 90, 'history': 80})
grades = student1.get_grades()
for key, value in grades.items():
print 'Marks in {}: {}'.format(key, str(value))
Which prints:
Marks in bio: 90
Marks in math: 100
Marks in history: 80
You can try something like:
student = Student("Edward", "Gates", "0456789", {"math": 100, "bio": 90, "history": 80})
And inside your constructor you can copy these values to a new dictionary:
class Student:
def __init__(self, firstName, lastName, id, grades):
self._firstName = firstName;
self._lastName = lastName;
self._id = id;
self._grades = grades.copy()
Notice that we're copying the dictionary to a new attribute because we want to avoid keeping a reference.
First, make sure to remove the semicolon ; from your code - it won't compile!
Second, I believe you're looking to do something like:
class Student:
def __init__(self, first_name, last_name, _id, **courses):
self._first_name = first_name
self._last_name = last_name
self._id = _id
self.courses = courses
def print_student(self):
print self._first_name
print self._last_name
print self._id
for key in self.courses:
print key, self.courses[key]
courses = {'math': 100, 'bio': 90, 'history': 80}
s = Student("John", "Smith", 5, **courses)
s.print_student()
OUTPUT
John
Smith
5
bio 90
math 100
history 80
I am very new to python and am really struggling to find a solution to this issue.
I just don't understand why I need to include only integers in my list when I though they are supposed to support multiple data types.
I've got a very simple field entry system for an account registration and I just can't add the items into a list.
Any help would be greatly appreciated. I've have included my code and the message I receive.
useraccounts = {}
group = []
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
group.append(user accounts)
This is the error message:
Traceback (most recent call last):
File "/Users/admin/Documents/Homework/Computing/testing/testing.py", line 11, in <module>
group['forename'] = forename
TypeError: list indices must be integers, not str
It looks like you want group to be a dict, and useraccounts to be a list. You have them backwards, as well as the append:
useraccounts = [] # <-- list
group = {} # <-- dict
forename = input('Forename: ')
surname = input('Surname: ')
DOB = input('DOB: ')
stu_class = input('Class: ')
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group) # <-- reversed. this will append group to useraccounts
As written, you were trying to append useraccuonts, an empty list, to group, a dict which has no append method
What you want is a dictionary:
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
In your original code useraccounts stays an empty dict that you just append to the list. If you wanted to add group to useraccounts:
useraccounts['key'] = group
group is a list, it cannot take string indices. It looks like you wanted to use a dictionary instead:
useraccounts = []
group = {}
group['forename'] = forename
group['surname'] = surname
group['dob'] = DOB
group['class'] = stu_class
useraccounts.append(group)
Note that you probably wanted useraccounts to be the list here; your code tried to call .append() on the group object..
or inline the keys and values directly into the dictionary definition:
useraccounts.append({
'forename': forename,
'surname': surname,
'dob']: DOB,
'class': stu_class})
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")