Keep first word of Python string? -
let's have list of full names, like:
names : ["katie von martin", "bob austin marley", "john travolta", "josh hartnett"]
what function split each string , retain first word like?
def keepfirstname(): name in names: ????
the easiest be:
def first_names(names): name in names: yield name.split()[0]
e.g.
>>> print list(first_names(["katie von martin", "bob austin marley", "john travolta", "josh hartnett"])) ['katie', 'bob', 'john', 'josh']
there few circumstances may not want split string if want first word ... e.g. if strings really long. in case, can use str.find
location of first space in string , can slice point give first name:
>>> def first_names(names): ... name in names: ... idx = name.find(' ') ... yield name[:idx] if idx > 0 else name ... >>> print list(first_names(["katie von martin", "bob austin marley", "john travolta", "josh hartnett"])) ['katie', 'bob', 'john', 'josh']
however, in practice, never necessary.
Comments
Post a Comment