Item
给定字符串,转换成“#”加字符串中的单词(首字母大写)
字符串为空或者字符长度超出140则返回False
题目来源:Codewars(5kyu)
题目原文:The marketing team is spending way too much time typing in hashtags.
Let’s help them with our own Hashtag Generator!
Here’s the deal:
It must start with a hashtag (#).
All words must have their first letter capitalized.
If the final result is longer than 140 chars it must return False.
If the input or the result is an empty string it must return False.
Example
例1:
原字符串:" Hello there thanks for trying my Kata";
应返回结果:"#HelloThereThanksForTryingMyKata"。
例2:
原字符串:"";
应返回结果:False。
Knowledge
- 数据类型:字符串、列表
- 运算符:赋值运算符
- 容器:列表
- 其他:For循环体、格式化函数、str.join()方法、str.capitalize()方法、re.split()方法
Parsing
- 题目细看则可发现与日记(十)的解答过程非常类似;
- 选择结构,满足条件返回字符串,不满足返回bool值;
- 为函数设定默认参数nullStr = False;
- 条件则是:输入的字符串长度大于140或者等于0
- 条件为true时,输出字符串先去除空格(split),然后遍历单词,且使用str.capitalize()方法转换首字母大写,最后使用str.join()转换合并
- 将if-else推导式进行简写,之后return返回。
Code
def generate_hashtag(s,nullStr = False):
return nullStr if len(s) == 0 or len(s) > 140 else "#"+"".join(i.capitalize() for i in s.split())