Reputation: 21
I need to create a program for my python instructor that processes a name and outputs it in the format "Last, First". The 2 different ways the user can input their name are, "first last"(no comma), or "last, first".
I've used my Python book but it does not help much when it comes to what the instructor wants from us to create.
space = name.index(' ')
first = name[0:1].upper()+name[1:space]
comma = name.index(',')
last = name[0:1].upper()+name[1:comma]
print(last + ', ' + first)
The correct result of this program should be "Last, First" as I stated already above. I keep getting the first name entered and the output is "name, name," (name is whatever is being inputted into the input statement) example.) user input --> 'joe bob' output --> 'Joe, Joe,'
Upvotes: 2
Views: 88
Reputation: 1228
So the simplest way is to user rstrip and split function getting the value in list and print it from index number
name = list(map(str, input().rstrip().split()))
print(name[1], name[0])
print(name[1] + ', '+ name[0])
Input
Firstname Lastname
OutPut
Lastname Firstname
lastname, Firstname
Upvotes: 0
Reputation: 1749
The mistake you did was first
and last
were assigned the same string.
I would suggest doing something like this:
name = 'Bob, joe'
if ',' in name:
last, first = name.split(',')
else:
first, last = name.split(' ')
print(last.strip().capitalize() + ', ' + first.strip().capitalize())
Hope this helps.
Upvotes: 1
Reputation: 128
In Python3, you can use the split()
method to convert a string into a list of words, separated by spaces.
This can be done by words = name.split()
.
Now, assuming that you have already learned string manipulation, you can remove the comma from the end of the first name (if there is), the first word in the words
list.
Then, simply print the list for first name and last name.
Good luck!
Upvotes: 0
Reputation: 3616
You can do something like this:
name = input("Write a name: ")
space_idx = name.index(' ')
if "," in name:
print(name)
else:
name = name[space_idx+1:] + ", " + name[:space_idx]
print(name)
Upvotes: 0