简体   繁体   中英

How do I find the initials of the name entered in this string?

Say the user enters "joe smith". I can find the J but I'm not sure how to find the S seeing that the length of the string can vary.

name=input("What is your name")
initials=(name[0],#not sure)
initials=initials.upper()
print(initials)

I had a question like this similar on a quiz and apparently I'm supposed to use indexing. Is that possible?

Use:

name = input("What is your name: ")
initials = ' '.join(map(lambda i: i.title(), name.split()))
print (initials)

or step by step:

name = input("What is your name: ")
splited_initials = name.split()  # ["joe", "smith"]
titled_initials = [item.title() for item in splited_initials]  # ["Joe", "Smith"]
initials = ' '.join(titled_initials)  # "Joe Smith"
print (initials)

This worked for me. It will print each inital on a new line so you may want to add to an array or something before printing:

name = input("what is your name?")
names = name.split()
for name in names:
  if name != "":
    print name[0]
name=input("What is your name")
initials=name.split(" ")
for word in initials:
  if word != "":
   print(word[0].upper())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM