初见Python解题之道(十一)

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

  1. 数据类型:字符串、列表
  2. 运算符:赋值运算符
  3. 容器:列表
  4. 其他:For循环体、格式化函数、str.join()方法、str.capitalize()方法、re.split()方法

Parsing

  1. 题目细看则可发现与日记(十)的解答过程非常类似;
  2. 选择结构,满足条件返回字符串,不满足返回bool值;
  3. 为函数设定默认参数nullStr = False;
  4. 条件则是:输入的字符串长度大于140或者等于0
  5. 条件为true时,输出字符串先去除空格(split),然后遍历单词,且使用str.capitalize()方法转换首字母大写,最后使用str.join()转换合并
  6. 将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())
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

顾平安6

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值