My input needs to be for example
name surname, street name 22b, 10000 Zagreb
and it need to output like this:
name and surname: name surname
Street: street name
street number: 22
house number: b
postal code: 100000
place: zagreb
and this is my code
whole_string =input("Person: ")
string_list = whole_string.split(", ")
split_street_and_street_number = string_list[1].split(" ")
postal_code_and_city = string_list[2].split(" ")
print(f"name and surname: {string_list[0]}")
print(f"street: {split_street_and_street_number[0]}")
print(f"street number: {split_street_and_street_number[1]}")
print(f"postal code: {postal_code_and_city[0]}")
print(f"city: {postal_code_and_city[1]}")
Please check out this.
import re
text = '22b'
street_number =" ".join(re.findall("[0-9]+", text))
house_number =" ".join(re.findall("[a-zA-Z]+", text))
print(street_number)
print(house_number)
You can find the index of the first letter and split the string using that index:
def find_index_of_first_letter(text):
for index, value in enumerate(text):
try:
int(value)
except ValueError:
return index
print('No letter in the text')
text = '22b'
first_letter = find_index_of_first_letter(text)
number, letters = text[:first_letter], text[first_letter:]
Related
Hello I'm trying to create a program that takes input and prints out the initials all uppercase but I can't figure out why my program is only printing the first letter of the last item of the list after string is split
this is my code:
full_name = input("Please enter your full name: ")
name = full_name.split()
for item in name:
new_name = item[0].upper()
print(new_name)
You can make a new, empty variable like initials and add the first letter to it
full_name = input("full name: ")
name = full_name.split()
initials = ""
for item in name:
initials += item[0].upper()
print(initials)
I think this can help you:
# get the full name from the user
full_name = input("Enter your full name: ")
# split the name into a list of words
name_list = full_name.split()
# loop through the list of words
for i in range(len(name_list)):
# get the current word
word = name_list[i]
# uppercase the first letter of the word
word = word[0].upper() + word[1:]
# replace the word in the list with the new word
name_list[i] = word
# join the list of words into a string
full_name = " ".join(name_list)
# print the full name
print(full_name)
My code below works as long as all of the student's name consists of only two names - ex. Julie Andrews. But, when generating the student's emails, I'm trying to account for the students who have two first names - ex. Mary Jane Stewart. I want it to output something like MJStewart123#gmail.org, vs. what my current code will print, which is MJane123#gmail.com - totally ignoring the student's last name.
After hours of researching Google, I have tried updating my create_emails fx to change my original variable first_last = name.split(" ") to something like first, middle, last = name.split(" ") or first_last = name.split(" ", 2) while also, respectively, updating the line utilizing the attribute .append from its original to student_emails.append(first_last[0][0] + first_last1 + first_last[2]+ last_three_sid + "#gmail.com") or student_emails.append(first[0] + middle[0] + last + last_three_sid + "#gmail.com"). All attempts have obviously returned some form of an error...
The attached Stack Overflow article is the closest thing I could find whose logic might be applicable to what I'm trying to accomplish here, specifically the comment by Manfred, but in reading it, I don't know how to apply what they've done to my program... because I don't quite understand what it is that I'm reading... since I'm such a newbie at all this. I'd appreciate any help you can offer.
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
first_last = name.split(" ")
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(first_last[0][0] + first_last[1] + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Finding and first and middle initials in a list of names in python
You could do it like this I guess:
student_names = []
def create_names():
count = 1
while count <= 5:
name = input("Enter student name, please. ")
student_names.append(name)
count += 1
create_names()
import random
student_ids = []
def create_ids():
student_id = random.randint(111111,999999)
return student_id
def create_id_list():
for name in student_names:
student_ids.append(create_ids())
create_id_list()
student_emails = []
def create_emails():
for name in student_names:
email_name = ""
first_last = name.split(" ")
for i, v in enumerate(first_last):
if i > len(first_last)-2:
break
email_name+=v[0]
email_name = email_name+first_last[-1]
sid = str(student_ids[student_names.index(name)])
len_sid = len(sid)
last_three_sid = sid[len_sid-3:len_sid]
student_emails.append(email_name + last_three_sid + "#gmail.com") #ignores last index if one is provided.
create_emails()
def student_info():
for name in student_names:
name_pos = student_names.index(name)
print("\n" + "name: " + name)
print("id: " + str(student_ids[name_pos]))
print("email: " + student_emails[name_pos])
student_info()
Result:
Enter student name, please. Julie Andrews
Enter student name, please. Mary Jane Stewart
Enter student name, please. Jack Hendricks
Enter student name, please. Maria Basset Juliett
Enter student name, please. Marco Hansen
name: Julie Andrews
id: 742536
email: JAndrews536#gmail.com
name: Mary Jane Stewart
id: 823274
email: MJStewart274#gmail.com
name: Jack Hendricks
id: 590875
email: JHendricks875#gmail.com
name: Maria Basset Juliett
id: 982168
email: MBJuliett168#gmail.com
name: Marco Hansen
id: 671240
email: MHansen240#gmail.com
The code is too redundant and could be implemented with some simpler structures.
name construction can use split combined with join function
storage can also use dictionaries to store multiple information about the same object, compared to multiple lists so more concise and efficient
The code itself is not a big problem, mainly the syntax structure requires more skilled,let's encourage each other in our endeavours
try this:
import random
info = []
# You can use for loop if you already know how many times it will loop
for i in range(5):
name = input("Enter student name, please:") # get name
student_id = random.randint(111111, 999999) # get id
name_structure = name.split()
email = "{name_abbr}{last_name}{sid}#gmail.com".format(
name_abbr="".join([item[0] for item in name_structure[:-1]]), # Generate initials
last_name=name_structure[-1], # Generate the last part of the name
sid=str(student_id)[-3:] # Generate the id in the mailbox
)
info.append({"name": name, "id": student_id, "email": email}) # Store to the list, or print directly
# Print Information
for item in info:
print("name:", item["name"])
print("id:", item["id"])
print("email:", item["email"])
print()
I need to write a program using parallel arrays. The program should ask the user to input a name then it will check if the name is in an existing array and if the name is in the array it will return the first name, the last name, the index where it was found in the array and the phone number. If there is more than a name that matches then it will return both of the names and their indexes.
This is what I have so far but I cannot seem to figure out how to get the index of the second duplicate.
name = ["David", "Tony", "Josh", "Chloe", "David", "Olivia"]
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]
for i in range(len(name)):
sName = input("Enter a Name: ")
if sName in name:
index = firstName.index(sName)
print(name[index],lastName[index],"is located at index",index)
print("Phone number:", phone[index])
print()
else:
print("The name:", sName, "does not exist in our records")
print("Please try a different name.")
print()
#The output should be something like:
#David Smith is located at index 0
#Phone number: 111-123-1234
#
#David Brown is located at index 4
#Phone number:555-123-1234
Here is a very simple solution to your problem.
name = ["David", "Tony", "Josh", "Chloe", "David", "Olivia"]
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]
found = False
sName = input("Enter a Name: ")
for i in range(len(name)):
if sName == name[i]:
print(name[i],lastName[i],"is located at index",i)
print("Phone number:", phone[i])
found = True
if found == False:
print("The name:", sName, "does not exist in our records")
print("Please try a different name.")
You do not need to use the index function because as you iterate the list using the for loop, if the target name is found a name[i], that value of i is the index of the target name. Additionally I moved
sName = input("Enter a Name: ")
outside the for loop. If it remains in the for loop, it only compares the target name with the name at the current index i.
In Python list index method, you can specify additional arguments:
start: from which index to start searching
end: upto which index should the item be searched
Once you find the first index, you can try searching again by setting start index just after the first occurrence index.
Reference: https://docs.python.org/3/tutorial/datastructures.html
Here is a function that could the job:
name = ["David", "Tony", "Josh", "Chloe", "David", "Olivia"]
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]
def findIndex(find_name, first_name):
pos = []
for x in range(len(first_name)):
if find_name == first_name[x]:
pos.append(x)
return pos
for i in range(len(name)):
sName = input("Enter a Name: ")
pos = findIndex(sName, name)
if len(pos) > 0:
for x in pos:
print(name[x],lastName[x],"is located at index",x)
print("Phone number:", phone[x])
print()
else:
print("The name:", sName, "does not exist in our records")
print("Please try a different name.")
print()
Here is a more pythonic function:
def findIndex(find_name, first_name):
return [x for x in range(len(first_name)) if find_name == first_name[x]]
You could also do something like this using the enumerate function:
lastName = ["Smith", "Jones", "Brown", "Miller", "Brown", "Williams"]
phone = ["111-123-1234","222-123-1234","333-123-1234","444-123-1234","555-123-1234","662-123-1234"]
sample_name = 'David Smith'
def find_details(full_name):
# Split the full name into first and last name
[first, last] = full_name.split(' ')
# check for the first name in the name list
for count, f_name in enumerate(name):
# if the first name is listed
if f_name == first:
# check if the last name at the same index is the last name we need
if lastName[count] == last:
phone_number = phone[count]
# we have found the person we need
print(f'{full_name} is located at position {count}. \nPhone number: {phone_number}\n')
return True
# Otherwise, we didn't find the name
print(f"The name: {full_name} does not exist in our records. \nPlease try a different name.\n")
return False
find_details('Josh Brown')
find_details('Delilah Le')
I need to define a search function for my code that searches for letters within my dictionary. I am only missing the actual 'search' loop and code. Many lines of code have been left out for ease of reading.
while True:
option = get_option()
...
elif (option == "S"):
search(users)
...
users = {}
def add(users):
student_number = input('Enter student number: ')
family_name = input("Enter family name: ")
first_name = input("Enter first name: ")
phone_number = input('Enter phone number: ')
single_info = {"student_number": student_number, "family_name": family_name, "first_name": first_name, "phone_number": phone_number}
users[student_number] = single_info
print("Record is added.")
...
family_name = input("Enter family name: ")
first_name = input("Enter first name: ")
# STN Name Phone
1 0123456 John Smith 111222
2 1111111 Mary Lee 001122
3 2222222 Hoa Zhang 334455
2 7676767 Milka Sjanovic 012012
This is the dictionary with the inputs, I require a search function to search for names within this.
expected output is
Search record by name.
Enter text to search: Mi
Search found 2 records.
# STN Name Phone
1 0123456 John Smith 111222
2 7676767 Milka Sjanovic 012012
You can traverse your dictionary using a comprehension to build a result set:
text = input("Enter text to search:").lower()
result = [ s for s in users.values() if text in (s["family_name"]+" "+s["first_name"]).lower() ]
print(f"Search found {len(result)} records")
for i,s in enumerate(result):
print(i+1,s["student_number"],s["first_name"],s["family_name"],s["phone_number"])
note: Given that you provided no usable test data, I just typed this in the answer box. You will need to fix any typos, and add formatting yourself
You could also separate the criteria definition from the search process like this:
criteria = lambda s:any(text in s[n].lower() for n in ["family_name","first_name"])
result = list(filter(criteria,users.values()))
This will give you more flexibility and the ability to easily create searches on other fields. For example, searching in any field:
criteria = lambda s: text in " ".join(s.values()).lower()
result = list(filter(criteria,users.values()))
I am working with an external file which has data in the form of:
-12345 CSEE 35000 Bart Simpson
-12346 CSEE 25000 Harry Potter
-12350 Economics 30000 Krusty The Clown
-13123 Economics 55000 David Cameron
With the first item being the ID, the second the subject, the third the salary, and the rest being the name of the person.
In part of my program I am trying to print the information of the people who have salaries between values submitted by the user. I have put all the data in a list called lecturers then I put all the salaries in a separate list called lecturers salary and tried to make them integers because at first I thought the reason the for loop wasn't working was because when trying to access them from the lectures loop I thought they might still be part of a string at this point.
I have already used a loop in my program to print all the people who teach a specific subject. This subject is submitted by the user. I tried to use a for loop again for the salaries but its not working.
print""
# To God be the Glory
lecturer = []
lecturer_salary = []
x = 0
a = " "
print ""
String = raw_input("Please enter the lecturers details: ")
print ""
def printFormat(String):
String = String.split()
lastname = String[-1]
firstnames = " ".join(String[3:-1])
name = ", ".join([lastname, firstnames])
ID_Subject = " ".join(String[0:2])
money = String[2]
print "%s,%s %s %s" % (lastname,firstnames,ID_Subject,money)
printFormat(String)
while x < len(lecturer):
lecturer_salary.append(int(lecturer [x][2]))
x = x + 1
print ""
try:
fname = input("Enter filename within " ": ")
with open(fname) as f:
for line in f:
data = line.split()
printFormat(line)
line = line.split()
lecturer.append(line)
except IOError as e :
print("Problem opening file")
print ""
print ""
answer = raw_input("Would you like to display the details of lectureers from a particular department please enter YES or NO: ")
if answer == "YES" :
print ""
department = raw_input("Please enter the department: ")
print ""
while x < len(lecturer) :
for line in lecturer:
if lecturer[x][1] == department:
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
**elif answer == "NO" :
print ""
answer2 = raw_input ("Would you like to know all the lecturers within a particular salary range: ")
print ""
if answer2 == "YES":
lower_bound = int(input("Please enter the lower bound of the salary range: "))
upper_bound = int(input("Please enter the upper bound of the salary range: "))
print ""
while x < len(lecturer) :
for line in lecturer_salary:
if lower_bound < lecturer_salary[x] < upper_bound :
print lecturer_salary[x]
x = x + 1**
else:
print ""
print "Please enter a valid input"
So, you have an array of lecturer and one of lecturer salary. the
for line in lecturer_salary:
is not needed - just the while followed by the if. Note that this will only print out the salary, not the lecturer details. Since x is the index to both arrays you can access lecturer[x] for the rest. In truth you don't need the lecturer_salary at all, just walk through lecturer and check:
while x < len(lecturer) :
if lower_bound < lecturer[x][2] < upper_bound :
a = lecturer[x]
a = ' '.join(a)
printFormat(a)
x = x + 1
For starters, you shouldn't name your variable with a capital letter like String or Id_Subject.
It is simpler to break code into functions and try using a dictionary or class to improve readability and extensibility.
Here is a minimal code using class:
lecturers = [] # To store Lecturer instances, which isn't necessary
class Lecturer():
def __init__(self, id, subject, salary, name):
self.id = id
self.subject = subject
self.salary = salary
self.name = name
def readfile(filename):
"""read each line in a file and yield a list of fields"""
with open(filename, "r") as f:
for line in f.readlines():
# return a list of fields
yield line.replace("\n", "").split()
def new_lecturer(detail):
"""Return a new lecturer instance from a list of fields"""
return Lecturer(detail[0],
detail[1],
detail[2],
{"firstname": detail[3],
"lastname": detail[4]
})
def print_lecturer_detail(lecturer):
"""Accept a lecturer instance and print out information"""
print "{0},{1} {2} {3}".format(lecturer.name["lastname"],
lecturer.name["firstname"],
lecturer.id,
lecturer.salary)
def main():
"""This is where all the main user interaction should be"""
fname = raw_input("Enter filename: ")
for lecturer in (readfile(fname)):
lecturers.append(new_lecturer(lecturer))
print ""
answer = raw_input("Would you like to display lecturers by department(Y/N)?: ")
if answer == "Y":
print ""
department = raw_input("Please enter the department: ")
print ""
for lecturer in lecturers:
if lecturer.subject == department:
print_lecturer_detail(lecturer)
elif answer == "N":
# implement salary code here
pass
if __name__ == '__main__':
main()
This may be an overkill now, but it's better than dealing with lists in a long run. You'll see that dealing with properties become much simpler. You may want to improve each function further and make it more modular and reusable.
#Paul Morrington has the straight answer on the while part.