python 核心编程 第六章习题

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
posted @ 2017-06-04 17:39  木易小邪  阅读(325)  评论(0编辑  收藏  举报