Friday, 30 March 2018

python - Extract First Name, Middle Name and Last Name

Input: 

       You need to read a line from STDIN to extract First Name, Middle Name and Last Name

Output: 

       First Name, Middle Name and Last Name (separated by a single comma)

Test Cases:

Input: Velraj Kutralam
Output: Velraj,,Kutralam

Input: vel raj kutralam
Output: vel,raj,kutralam

Program:

#input function in Python 2.7, evaluates whatever your enter, as a Python expression(that is python variable).
# If you simply want to read strings, then use raw_input function in Python 2.7, which will not evaluate the read strings.
line = raw_input("Enter the string:")
print line
#comma = ','.join(line)

spl = line.split()      # convert the list of array into an separated string
print spl
spl_for_com = spl[:3]  # copy the first 3 string
print spl_for_com

leng = len(spl_for_com)
#print leng

if(leng == 2):
    join = ',,'.join(spl_for_com)
else:
    join = ','.join(spl_for_com)

remainin = ' '.join(spl[3:])
#remainin = spl[3:].split()
result = join + ' ' + remainin
print "After join = %s " % result
print "Read value = %s " % line


Output:

$ python readStdin-str-opr.py
Enter the string:velraj kutralam
velraj kutralam
['velraj', 'kutralam']
['velraj', 'kutralam']
After join = velraj,,kutralam
Read value = velraj kutralam

No comments:

Post a Comment