Home > Blockchain >  Get first two character of first name AND first character of last name in Python using Indexing and
Get first two character of first name AND first character of last name in Python using Indexing and

Time:02-03

I Would like to store in a variable the first 2 chars of a first name and then the first char of a last name in Python. I have to use the Splice() along with the indexing.

For example: John Doe --> JoD

I am pretty new to Python, and this is what I have come up to so far.


def getCharsOfName(name):
  initials= ""
  for c in name:
    initials  = c[0]
  print(initials)

  
name = input("Enter your name (in two words)")
name = name.split(' ')
getCharsOfName(name)

Output --> JD (should be JoD)

I defined a function for this operation.

I can only manage to print the initials right now, I thought to include a condition on the second pass of the for loop but I could not find a proper solution.

Has anybody an idea on how I could make this work ?

Thank you,

CodePudding user response:

Use split along the space. Then use list_after_split[0][0:2] for the firstname, and list_after_split[1][0:1] for the lastname. Then just join (add) the two strings together.

  •  Tags:  
  • Related