checkio练习题:first-word

本文介绍了一种从给定字符串中查找并返回第一个单词的方法,特别关注了如何处理字符串中的特殊字符,如点、逗号和撇号。通过正则表达式实现,确保了即使在文本开始于非字母字符的情况下也能正确提取单词。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

You are given a string where you have to find its first word.

When solving a task pay attention to the following points:

There can be dots and commas in a string.
A string can start with a letter or, for example, a dot or space.
A word can contain an apostrophe and it's a part of a word.
The whole text can be represented with one word and that's it.
Input: A string.

Output: A string.

Example:

first_word("Hello world") == "Hello"
first_word("greetings, friends") == "greetings"
1
2
How it is used: the first word is a command in a command line

Precondition: the text can contain a-z A-Z , . '

您将获得一个字符串,您必须找到它的第一个单词。
解决任务时要注意以下几点:
字符串中可以有点和逗号。
字符串可以以字母开头,例如点或空格。
一个单词可以包含撇号,它是单词的一部分。
整个文本可以用一个词来表示,就是这样。
输入:一个字符串。
输出:一个字符串。

 

import re


def first_word(text: str) -> str:
    """
        returns the first word in a given text.
    """
    # your code here
    # code 1
    # return text.strip().replace(',', ' ').replace('.', ' ').split()[0]
    # code 2
    return re.search("([\w']+)", text).group(1)
    # code 3
    # return re.search("[a-zA-Z']+", text).group()

if __name__ == '__main__':
    print("Example:")
    print(first_word("Hello world"))
    
    # These "asserts" are used for self-checking and not for an auto-testing
    assert first_word("Hello world") == "Hello"
    assert first_word(" a word ") == "a"
    assert first_word("don't touch it") == "don't"
    assert first_word("greetings, friends") == "greetings"
    assert first_word("... and so on ...") == "and"
    assert first_word("hi") == "hi"
    assert first_word("Hello.World") == "Hello"
    print("Coding complete? Click 'Check' to earn cool rewards!")

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值