简体   繁体   English

编写一个 function 打印字符串中第一个空格后的第一个单词

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

Programming Challenge 5: Write a Python function called secondword.编程挑战 5:编写一个名为 secondword 的 Python function。 The function should take a single input that will be a string. function 应该接受一个字符串输入。 If there is no space character in the string, the function should output an empty string (a string with no characters between the quotes).如果字符串中没有空格字符,function 应该是一个空字符串(引号之间没有字符的字符串)output。 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.如果字符串中有一个空格字符,则 function 应该 output 一个包含该空格之后的输入字符串切片的字符串。 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.如果字符串中有两个或多个空格字符,则 output 应该是输入字符串中第一个空格之后直到但不包括第二个空格的切片。

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 ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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