Reputation: 21
I am trying to return the value M from Mr. Smith but whenever I run my code below it returns ''
>>>name = input("Please input your name: ")
Please input your name: Mr. Smith
>>> if name == name.find(' ') and name.isalpha():
get_initial = name[0]
>>>get_initial
''
Upvotes: 0
Views: 71
Reputation: 1318
python 3
name = input("Please input your name: ")
c=name.strip()[0]
if c.isalpha():
print(c)
python 2 :
>>> name = raw_input("Please input your name: ")
Please input your name: Hisham
>>> c=name.strip()[0]
>>> if c.isalpha():
print c
output py3:
Python 3.5.2 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Please input your name: dsfgsdf
d
output py2:
H
Upvotes: 2
Reputation: 215
Assuming you have to find the first character of a name....
def find_initial(name):
i = 0
initial_name_size = len(name)
while True:
name = name[i:]
if name.isalpha():
get_initial = name[0]
return get_initial
else:
i = i+1
if i >= initial_name_size:
return 'There is no initial'
name = input("Please input your name: ")
print find_initial(name)
Upvotes: 0
Reputation: 4925
I see a lot of problems in this proposed code.
First of all, input()
evaluates the input string as a python expression and that's not what you want, you need to use raw_input()
instead.
Second, isalpha()
won't return True if input includes '.' or spaces, so you need to find another metric, for example, if only alphabetical characters are allowed, you can use isalpha()
this way:
name_nospaces = "".join(name.split())
if name_nospaces.isalpha():
...
Then, it doesn't make much sense to do name == name.find(' ')
, just have:
if name.find(' '):
...
Upvotes: 0