当前位置:首页 >> 编程语言 >> 【Python CheckiO 题解】Correct Sentence,fulltao

【Python CheckiO 题解】Correct Sentence,fulltao

0evadmin 编程语言 1
文件名:【Python CheckiO 题解】Correct Sentence,fulltao 【Python CheckiO 题解】Correct Sentence

CheckiO 是面向初学者和高级程序员的编码游戏,使用 Python 和 JavaScript 解决棘手的挑战和有趣的任务,从而提高你的编码技能,本博客主要记录自己用 Python 在闯关时的做题思路和实现代码,同时也学习学习其他大神写的代码。

CheckiO 官网:https://checkio.org/

我的 CheckiO 主页:https://py.checkio.org/user/TRHX/

CheckiO 题解系列专栏:https://itrhx.blog.csdn.net/category_9536424.html

CheckiO 所有题解源代码:https://github.com/TRHX/Python-CheckiO-Exercise


题目描述

【Correct Sentence】:给定一个字符串,将其转换成正确的句子:如果原字符串中,首字母是小写,则将其转换成大写,句尾如果没有句号(.),则要加个句号,如果原字符串中,首字母是大写,则新字符串中不变,如果句尾有句号,则新字符串句尾也不变。

【链接】:https://py.checkio.org/mission/correct-sentence/

【输入】:字符串

【输出】:字符串

【前提】:原字符串中只包含 a-z A-Z , . 和空格

【范例】:

correct_sentence("greetings, friends") == "Greetings, friends."correct_sentence("Greetings, friends") == "Greetings, friends."correct_sentence("Greetings, friends.") == "Greetings, friends." 解题思路

用 islower() 方法判断第一个字母是否为小写字母,若是小写字母,则用 upper() 方法将其转换成大写字母,利用切片 text[1:],将转换后的第一个字母和剩下的字符拼接起来,组成新的字符串。

用 text[-1] 获取最后一个字符,如果最后一个字符不是 .,则在整个字符串后面加上 .

最后返回处理过后的新字符串即可

代码实现 def correct_sentence(text: str) -> str:"""returns a corrected sentence which starts with a capital letterand ends with a dot."""if text[0].islower():text = text[0].upper() + text[1:]if text[-1] != '.':text += '.'return textif __name__ == '__main__':print("Example:")print(correct_sentence("greetings, friends"))# These "asserts" are used for self-checking and not for an auto-testingassert correct_sentence("greetings, friends") == "Greetings, friends."assert correct_sentence("Greetings, friends") == "Greetings, friends."assert correct_sentence("Greetings, friends.") == "Greetings, friends."assert correct_sentence("hi") == "Hi."assert correct_sentence("welcome to New York") == "Welcome to New York."print("Coding complete? Click 'Check' to earn cool rewards!") 大神解答 大神解答 NO.1 correct_sentence=lambda s: (s[0].upper() if ~-s[0].isupper() else s[0])+s[1:]+('.' if s[-1]!='.' else '') 大神解答 NO.2 return ((text[0].upper() + text[1:]) if (text[0].islower() == True) else text) + ("." if text[-1]!= "." else "") 大神解答 NO.3 correct_sentence=lambda t:t[0].upper()+t[1:]+'.'*(t[-1]!='.')
协助本站SEO优化一下,谢谢!
关键词不能为空
同类推荐
«    2025年12月    »
1234567
891011121314
15161718192021
22232425262728
293031
控制面板
您好,欢迎到访网站!
  查看权限
网站分类
搜索
最新留言
文章归档
网站收藏
友情链接