首页 > 编程语言 > 详细

python 核心编程 第六章习题

时间:2017-06-04 19:49:12      阅读:283      评论:0      收藏:0      [点我收藏+]

6-6 创建一个类似 string.strip() 函数

方法一 低效方法 大量复制和生成子串对象

def str_strip(s):
  while len(s)>=2:
    if s[0]==‘ ‘:
      s=s[1:]
    else:
      break
  while len(s)>=2:
    if s[-1]==‘ ‘:
      s=s[:-1]
    else:
      break
  if s==‘ ‘ or s==‘‘:
    return ‘‘
  else:
    return s

方法二: 转换成列表

def str_strip(s):

    if s == " " or s == "":
return ""
#to list
elif len(s)>=2:
l = list(s)
while l and l[0] == " ":
l.pop(0)
while l and l[-1] == " ":
l.pop(-1)
if l:
return "".join(l)
else:
return ""
else:
return s

6-10.
字符串。写一个函数,返回一个跟输入字符串相似的字符串,要求字符串的大小写反转,比如,输入“Mr.Ed”,应该返回“mR.eD”作为输出。

input = raw_input(‘Please input a string: ...‘)
output = ‘‘
for i in input:
if i == i.upper():
output = output + i.lower()
else:
output = output + i.upper()
print output

python 核心编程 第六章习题

原文:http://www.cnblogs.com/muyiblog/p/6941217.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!