简体   繁体   中英

Write a function that prints the first word after the first space in a string

Programming Challenge 5: Write a Python function called secondword. The function should take a single input that will be a string. If there is no space character in the string, the function should output an empty string (a string with no characters between the quotes). If there is a single space character in the string, the function should output a string containing the slice of the input string that is after that space. If there are two or more space characters in the string, the output should be the slice of the input string after the first space up to but not including the second space.

For example:

secondword("United")
should return ''
second word("United States")
should return 'States'
secondword("United States of America")
should return 'States'

Easily done with re - good luck with the challenge

import re
def secondword(s):
    p = r' ([^ ]*)'
    m = re.search(p, s)
    return m[1] if m else ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM