I have been working on a program which asks the user to type in a list of names. After they have typed in those names, my program has to right align all of those names. This is what I have so far:
names =[]
# User is prompted to enter a list of names
name = input ("Enter strings (end with DONE):\n")
while name != 'DONE':
names.append(name) # This appends/adds the name(s) the user types in, to names
name = input("")
print("\n""Right-aligned list:")
for name in names:
maximum = max(names, key=len) #This line of code searches for the name which is the longest
new_maximum = len(maximum) #Here it determines the length of the longest name
diff = new_maximum - len(name) #This line of code is used to subtract the length of the longest name from the length of another different name
title = diff*' ' #This code determines the open space (as the title) that has to be placed in front of the specific name
print(title,name)
Here is the program without all of the comments:
names =[]
name = input ("Enter strings (end with DONE):\n")
while name != 'DONE':
names.append(name)
name = input("")
print("\n""Right-aligned list:")
for name in names:
maximum = max(names, key=len)
new_maximum = len(maximum)
diff = new_maximum - len(name)
title = diff*' '
print(title,name)
The output I want for this program is:
Enter strings (end with DONE):
Michael
James
Thabang
Kelly
Sam
Christopher
DONE
Right-aligned list:
Michael
James
Thabang
Kelly
Sam
Christopher
Instead this is what I get:
Enter strings (end with DONE):
Michael
James
Thabang
Kelly
Sam
Christopher
DONE
Right-aligned list:
Michael
James
Thabang
Kelly
Sam
Christopher
NB:The moment the user types in DONE, the prompt ends.
The problem is that there is an extra space printed for every name in the list. How can I print it right-aligned but without the extra spaces?
You can use string formatting as follows:
a = ['a', 'b', 'cd', 'efg']
max_length = max(len(i) for i in a)
for item in a:
print '{0:>{1}}'.format(item, max_length)
[OUTPUT]
a
b
cd
efg
I know this is an old question, but this will get it done in one line:
print('\n'.join( [ name.rjust(len(max(names, key=len))) for name in names ] ))
This SO answer for list comprehension helped me: Call int() function on every list element?
Related
The Problem -
If I input more than one player's names. Only the first name comes up and the program then stops.
What can I do to print all names and the W/R Percentage presented by User's Input.
The code -
def print_player_data():
nba_data = pd.read_csv("csv_data.csv", sep=",")
dataList = []
player_names = input("Enter a list of player names: ")
player_names = player_names.split(",")
print(player_names)
for player in player_names:
for index, row in nba_data.iterrows():
if row["PLAYER_NAME"] == player:
dataList.append(row["W/R_percentage"])
print(dataList)
print_player_data()
The Data -
PLAYER_NAME,TEAM_ABBREVIATION,Player Impact Rating,GP,Wins,Losses,W/R_percentage
Alex Len,ATL,0.1,77,28,49,36.36
Alex Poythress,ATL,0.069,21,7,14,33.33
Daniel Hamilton,ATL,0.07,19,7,12,36.84
DeAndre Bembry,ATL,0.081,82,29,53,35.37
It seems like when inputting the names, you add spaces after the comma.
Add this line before iterating through your list to remove leading whitespaces:
player_names = [name.lstrip() for name in player_names]
I have a text file called listofhotelguests.txt where hotelguests are stored line by line with their first names separated by && as a delimiter. Can someone explain how I can have my Python program read it so it associates john with doe, ronald with macdonald, and george with washington?
My expected outcome I'm hoping for is if I prompt the user for their lastname to make sure their a valid guest on the list, the program will check it against what it has in the file for whatever the firstname they entered earlier was.
So if someone enters george as their first name, the program retrieves the line where it has george&&washington, prompts the user to enter their lastname and if it doesn't match what it has, either say it matches or doesn't. I can figure the rest out later myself.
Assuming there is nobody with the same names.
I know I have to split the lines with &&, and somehow store what's before && as something like name1 and whats after && as name2? Or could I do something where if the firstname and lastname are on the same line it returns name1 and password1?
Not sure on what to do. Python is one of my newer languages, and I'm the only CS student in my family and friend groups, so I couldn't ask anybody else for help. Got nowhere by myself.
Even just pointing me in the direction of what I need to study would help immensely.
Thanks
Here's what the text file looks like:
john&&doe
ronald&&macdonald
george&&washington
abraham&&lincoln
Here's some pseudocode:
listoffirstnames = []
listoflastnames= []
with open ("listofhotelguests.txt") as guestlist:
for line in guestlist
listoffirstnames.append()
listoflastnames.append()
while True:
firstname = input("Please enter your firstname")
if (firstname in listoffirstnames):
print("Hello" ,firstname)
break
else:
print("Sorry, you weren't in the list. Please try again")
while True:
print("Hello " + firstname + " please enter your last name.")
lastname = input("Enter lastname to verify guest status: ")
if (lastname in listoflastnames):
print("Welcome back!" + firstname + lastname)
break
else:
print("Sorry, the lastname was entered wrong")
Here's a solution:
first_names = []
last_names = []
with open("bruh.txt") as f:
for line in f:
name = line.strip().split("&&")
first_names.append(name[0])
last_names.append(name[1])
print(first_names)
print(last_names)
Basically, strip() removes any pesky unwanted spaces on either end, and the split() function allows you to split a string based on the parameter, here &&. So name ends up storing the first and last name as a list, and you can access them through subscripts.
That said, a long-term better solution would be to store both the first and last names together as a list, inside a bigger list of all names. For example,
names = [['john', 'doe'], ['firstname', 'lastname'], ...]
For that you can use this:
names = []
with open("bruh.txt") as f:
for line in f:
name = line.strip().split("&&")
names.append(name)
print(names)
Which outputs: [['john', 'doe'], ['ronald', 'macdonald'], ['george', 'washington'], ['abraham', 'lincoln']]
Admittedly, this does require more code to access all first and last names separately, but as I said, the convenience of having both parts of the name as part of a single list of names is a better long term approach.
I have an assignment where I have a list with two names and I have to print the first name and then I have to print the last name.
names_list = ['Oluwaferanmi Fakolujo', 'Ajibola Fakolujo']
I have two names and then when I find the whitespace between them I have to print both the first name and the last name out of the list and put it into a variable.
I have tried to slice it but I don't understand it enough to use it. Here is an example:
substr = x[0:2]
This just brings both names instead of only substring it.
names_list = ['Oluwaferanmi Fakolujo', 'Ajibola Fakolujo']
for i in range(0, len(names_list)):
nf = names_list[i].split(' ')
name = nf[0]
family = nf[1]
print("Name is: {}, Family is: {}".format(name, family))
Output:
Name is: Oluwaferanmi, Family is: Fakolujo
Name is: Ajibola, Family is: Fakolujo
This will only work for Python 3.x
You can use the split() method and indexing for these kinds of problems.
Iterate through the list
split() the string
Store the values in a variable, so that we can index them
Display the values
names_list = ['Oluwaferanmi Fakolujo', 'Ajibola Fakolujo']
for i in names_list:
string = i.split(" ")
first_name = string[0]
last_name = string[1]
print(f"First Name: {first_name} Last Name: {last_name}")
guys I'm a beginner who is new to Python.
I want to create mthod which find duplicate name in list. So, I created it but it doesn't work the way I want.
This is my code
def find_same_name(name) :
result = set()
for i in range(0 , len(name) - 1) :
for j in range(i + 1, len(name)) :
if name[i] == name[j] :
result.add(name[i])
return result
name = input("Please Write Name ")
print(name)
#print(type(name))
print(find_same_name(name))
And this is my result
Please Write Name Tom Jerry Mike Tom Kim
Tom Jerry Mike Tom Kim
{'T', 'o', ' ', 'e', 'r', 'i', 'm'}
Why it print as type character? I don't know what is wrong. Would you guys pleas help me?
The reason is that you are iterating over each letter in the list, not every name. To iterate over every name you can use the .split() function which splits a string into a list based on (by default) the spaces.
def find_same_name(name) :
allnames = name.split()
result = set()
for i in range(0 , len(allnames) - 1) :
for j in range(i + 1, len(name)) :
if allnames[i] == allnames[j] :
result.add(name[i])
return result
name = input("Please Write Names: ")
print(name)
print(find_same_name(name))
name = input("Please Write Name ").split(' ')
It is a simple mistake you made.
You are using the name as a string instead of list of names. Use 'split' to make the given names into list and apply the function
name = input("Please Write Name ")
This line assign name as a string. So when you do name[i] in the function, it returns a single letter.
To solve that, assign name as a list:
name = input("Please Write Name ").split()
The split() method transforms the string with seperate names into a list that records all seperate name, so you can use name[i] to get the names.
Hello and welcome to stackoverflow.
your problem is, that you want to hand over a list of names to your method, but your are currently hand over a single string "Tom Jerry Mike Tom Kim Tom Jerry Mike Tom Kim". If you do this, python will access the single letters withing the string and not the words. I guess, you want to split the input on spaces, which can be done by:
name = input("Please Write Name ")
name_list = name.split(" ")
print(name_list)
print(type(name)) # will be list now, not str
print(find_same_name(name_list))
I'm having trouble creating a program which takes a list of first names and a list of last names, appends the two lists and adding #abc.mail.com
I haven't touched python in months so I don't even know what to do anymore. I tried creating lists and dictionaries but I don't know if it's even possible to input more than one string at a time.
To summarize:
I want a program that asks for a user to input a list for firstName, a list for lastName and then the program to append it together to make firstName.lastName#abc.mail.com
I appreciate any help that you give.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def fill_list(l, promt):
while True:
x = input(promt)
if not x:
break
l.append(x)
if __name__ == '__main__':
first_names = list()
last_names = list()
fill_list(first_names, "Input first name: ")
print('first_names: {}'.format(first_names))
fill_list(last_names, "Input last name: ")
print('last_names: {}'.format(last_names))
for first, last in zip(first_names, last_names):
print('{}.{}#abc.mail.com'.format(first, last))
Output:
Input first name: fff
Input first name: ddd
Input first name: ggg
Input first name:
first_names: ['fff', 'ddd', 'ggg']
Input last name: 111
Input last name: 222
Input last name: 333
Input last name:
last_names: ['111', '222', '333']
fff.111#abc.mail.com
ddd.222#abc.mail.com
ggg.333#abc.mail.com
I'm giving you a very simple solution minus any fancy methods or comprehensions.
You seem to be a Python beginner.
Try :
fnames = []
lnames = []
#specify a size - depends on how many names you want; ideally first and last names would match right?
len_fnames = 3
len_lnames = 3
#input loop for first names
while len(fnames) < len_fnames:
f = raw_input('Enter a first name')
fnames.append(f)
print fnames
#input loop for last names - you can run this once to get both first and last names
while len(lnames) < len_lnames:
l = raw_input('Enter a last name')
lnames.append(l)
print lnames
#a list of the generated email IDs
email = []
for i, f in enumerate(fnames):
email.append(f + "." +lnames[i] + "#abc.mail.com")
print email
See Martin's solution below - it's far more elegant and the right way to do it.