语法练习:front3

语法练习:front3

题目:front3

Given a string, we’ll say that the front is the first 3 chars of the string. If the string length is less than 3, the front is whatever is there. Return a new string which is 3 copies of the front.

front3(‘Java’) → ‘JavJavJav’
front3(‘Chocolate’) → ‘ChoChoCho’
front3(‘abc’) → ‘abcabcabc’

我的解答:

def front3(str):
  if len(str) < 3:
    return str*3
  else:
    return (str[:3]*3)

Expected Run
front3(‘Java’) → ‘JavJavJav’ ‘JavJavJav’ OK
front3(‘Chocolate’) → ‘ChoChoCho’ ‘ChoChoCho’ OK
front3(‘abc’) → ‘abcabcabc’ ‘abcabcabc’ OK
front3(‘abcXYZ’) → ‘abcabcabc’ ‘abcabcabc’ OK
front3(‘ab’) → ‘ababab’ ‘ababab’ OK
front3(‘a’) → ‘aaa’ ‘aaa’ OK
front3(‘’) → ‘’ ‘’ OK

All Correct

标答:

def front3(str):
  # Figure the end of the front
  front_end = 3
  if len(str) < front_end:
    front_end = len(str)
  front = str[:front_end]
  return front + front + front 
  
  # Could omit the if logic, and write simply front = str[:3]
  # since the slice is silent about out-of-bounds conditions.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值