user7253631
user7253631

Reputation:

Python String Split Order Wrong

My current code

defname,last_name):
    if not isinstance(reg, int) or \
       not isinstance(year, int) or \
       not isinstance(degree, str) or \
       not isinstance(other_name, str) or \
       not isinstance(last_name, str) :
       print("Invalid string argument")
    elif 0<=year<=4:
        l.append((reg,year,degree,other_name,last_name))
    else: print("Invalid year")

def p
    reg,year,degree,other_name,last_name = student.strip().split(" ",4)
    reg=int(reg)
    year=int(year)
    fullName=last_name+ ", " + other_name
    thisYear="Year " + str(year)
    print(format(fullName, "<32s")+format(reg,"<7d")+format(degree,">6s"),format(thisYear,">6s"))

how can I do this effectively with the right formats? I am trying to make it so it uses both functions and is checking for valid

Upvotes: 1

Views: 375

Answers (3)

Quan Vuong
Quan Vuong

Reputation: 1989

This is because you are limiting the number of splits to 4.

Thus, for the third line, the 4th space that gets split is between "Homer" and "J". Thus, "J" and "Homer" are in the same string after the split.

https://www.tutorialspoint.com/python/string_split.htm

Upvotes: 0

user3030010
user3030010

Reputation: 1857

Well, for the reason it's printing on that side, that's because of the way you called .split(). Calling it with the 4 will of course restrict it to splitting 4 times. And since it splits from left to right, once it has made its 4th split (ie. after 'Homer'), it will simply return the rest of the string as a whole (ie. 'J Simpson').

If I were you, I would do it like this:

reg,year,degree,*name = student.strip().split(" ")
name = list(reversed(name))
fullname = name[0] + ', ' + ' '.join(name[1:])

Doing *name lets you grab multiple tokens as a list, and then process them however you like.

Upvotes: 1

TurnipEntropy
TurnipEntropy

Reputation: 527

First off, wouldn't you want it to print Simpson, Homer J?

Secondly, it prints it J Simpson, Homer because this is what your list looks like:[1342347, 2, G401, Homer, J Simpson]. It splits it this way because you told it to split at each space it sees, and to make a maximum of 4 separate strings. It doesn't know that middle names belong to other_name, so you have to do a little more work in your string parsing to get that to behave as desired.

Upvotes: 0

Related Questions