2019/9/28_codewars自虐_输出单词的中间字母

**题目原文:**You are going to be given a word. Your job is to return the middle character of the word. If the word’s length is odd, return the middle character. If the word’s length is even, return the middle 2 characters.

#Examples:

Kata.getMiddle(“test”) should return “es”

Kata.getMiddle(“testing”) should return “t”

Kata.getMiddle(“middle”) should return “dd”

Kata.getMiddle(“A”) should return “A”
#Input

A word (string) of length 0 < str < 1000 (In javascript you may get slightly more than 1000 in some test cases due to an error in the test cases). You do not need to test for this. This is only here to tell you that you do not need to worry about your solution timing out.

#Output

The middle character(s) of the word represented as a string.

**感觉这道题比较简单,直接先读取字符串长度,然后分为奇数偶数讨论,直接用字符串的索引方式输出即可
给出自己写的最简单最清晰的代码:

def get_middle(s):
    	length=len(s)
    	print(length)
    	if length%2==0:
        	return(s[int(length/2-1)]+s[int(length/2)])
get_middle("smooth")**

这里要注意的是Python和C语言不同,Python可以直接使用len(string)方法获得字符串长度,并且可以用类似于索引的方式输出字符串的第几个字符(一个字符对应一个索引),这一点比C语言方便很多
另外要注意:Python的字符串索引一定要是整数,这里length/2以后int直接被转换成了float,所以一直报错,要用int()进行强制转换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值