How to get the first word in the string

后端 未结 6 827
梦毁少年i
梦毁少年i 2020-12-05 04:07

text is :

WYATT    - Ranked # 855 with    0.006   %
XAVIER   - Ranked # 587 with    0.013   %
YONG     - Ranked # 921 with    0.006   %
YOUNG    - Ranked # 8         


        
6条回答
  •  攒了一身酷
    2020-12-05 04:26

    If you want to feel especially sly, you can write it as this:

    (firstWord, rest) = yourLine.split(maxsplit=1)
    

    This is supposed to bring the best from both worlds:

    • optimality tweak with maxsplit while splitting with any whitespace
    • improved reliability and readability, as argued by the author of the technique.

    I kind of fell in love with this solution and it's general unpacking capability, so I had to share it. :)

提交回复
热议问题