0

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
''
4
  • 1
    str.find returns the index of character(s) in the string. Do you know that? Commented Oct 14, 2016 at 23:46
  • I do now that but the name could vary so I want to know how to find the first index value of any given name input Commented Oct 14, 2016 at 23:50
  • You probably want to strip your string input. This removes whitespace from both ends. name = name.strip(); name[0]. Unless you want to keep the whitespace Commented Oct 15, 2016 at 0:03
  • Please, start with a tutorial… Commented Oct 15, 2016 at 0:07

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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(' '):
    ...

Comments

0

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)

1 Comment

input: Madam. Tusade output: T

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.