Reputation: 33
In my program I am asking the name of a person. Then I splice the strings to only have their initials.
# Ask for names
first=input('Please enter your first name: ')
middle=input('Please enter your middle name: ')
last=input('Please enter your last name: ')
# Splice
first[1]
middle[1]
last[1]
The Program gives an error when splicing the middle name is a person left it blank. Can someone help me solve the error?
Upvotes: 3
Views: 74
Reputation: 9969
When a string is empty, it will have no characters so accessing any index raises errors. You need to test if the string is empty before taking an index. if middle
is the easiest way to test as that evaluates as False
if the string is empty.
if middle:
middle[0]
Note that [1]
will take the second element, as indexing starts at 0, not 1. So you want [0]
. Also, this is indexing, not slicing. Slicing is when you take a series of values from the string, indexing is when you access a single character.
Upvotes: 1
Reputation: 22954
When you are not sure if the user may input a blank string or a valid name then best way is to use an if - else
construct, or if you want to do it more pythonically then you may try:
>>> middle = "anmol"
>>> middle[1:2]
>>> "n"
>>> middle = ""
>>> middle[1:2]
>>> "" # No error here.
Upvotes: 0