top of page

Python (6): Strip & Split




Today I'd would like to introduce two python functions that can help you clear blank spaces in the head and tail, and split strings into a list using delimiter.



Let's see an example:


def lastwordlen (self, s)
{
    return len(s.strip().split(" ")[-1])
} 


s is the input string from test cases.


lastwordlen defines a function that returns the length of the last word of s.


strip() removes all blank spaces at the beginning and the end of s.


It's to make sure that no blank space exsists at the end of s.


In this way, the last word would always be a real word instead of a blank space.


split(" ") splits the string in s into a list using delimiter " ".


It means all words that are seperated with a " " blank space would be deemed as two different words and being split.


[-1] means the word that would be returned is the one with index -1, which is the last word of the list.


Finally, we use len() to cover the whole line.


It'll then return the length of the last word in s.









Congratulations on completing the tutorial!


Don't get discouraged if everything didn't sink in perfectly the first time through - absorbing a new programming language and its many features takes time and practice.



See you in Python (7)!








© 2023 Harmony Pang. All rights reserved.








Comentários


bottom of page