习题6:py2 :声明str类型变量和unicode变量,将unicode变量变为2个str变量(gbk,utf-8各一次)将utf-8编码的str类型,转换为gbk
>>> s='中国'
>>> type(s)
<class 'str'>
>>> s.encode('utf-8')
b'\xe4\xb8\xad\xe5\x9b\xbd'
>>> s.encode('gbk')
b'\xd6\xd0\xb9\xfa'
>>> s.encode('utf-8').decode('utf-8').encode('gbk')
b'\xd6\xd0\xb9\xfa'
习题7:判断一个输入的句子中有多少个字母
11句子中全是字母
num=0
stence="We'll be there on the double"
for i in stence:
if 'a'<= i <='z' or 'A' <= i <='Z':
num+=1
22句子中全是字母
def judgeLetters(sentence):
lettersnum = 0
if not isinstance(sentence,str):
return None
for i in range(len(sentence)):
if ord(sentence[i]) in list(range(97,123)) or ord(sentence[i]) in list(range(65,91)):
lettersnum += 1
return lettersnum
sentence=input("输入句子:")
print(judgeLetters(sentence))
习题8: 26个字母大小写成对打印,例如:Aa,Bb....
11输出成对字母列表
letterlist=[]
for i in range(26):
letterlist.append(chr(i+65)+chr(i+97))
22输出成对字母的字符串
def upperAndLower():
s=''
for i in range(1,27):
s+=chr(i+64)+chr(i+96)
return s
print(upperAndLower())
33成对字母的输出
def upperAndLower():
listletters=[]
for i in range(1,27):
listletters.append(chr(i+64)+chr(i+96))
for j in listletters:
print(j,end=',')
print(upperAndLower())
习题9、一个list包含10个数字,然后生成新的list,要求,新的list里面的数都比之前的数多1
11输出比原列表多1的列表
lista=[2,3,4,5,6,87,34,9,0,3]
list(map(lambda x:x+1,lista))
22封装成函数,输出比原列表多1的列表
def baseAddOne(listnum):
if not isinstance(listnum,list):
return None
g=lambda x:x+1
addonelist=list(map(g,listnum))
return addonelist
listnum=[1,2,3,4,5,6,7,7,54,324]
print(baseAddOne(listnum))
习题10、倒序取出每个单词的第一个字母。
11逆序输出每个单词的第一个字母
stence="We'll be there on the double"
for i in stence.split()[::-1]:
print(i[0])
22封装成函数
def reverseOutputFirstword(stence):
stencelist=(stence.strip('.').replace(',',' ').split())[::-1]
for i in stencelist:
print(i[0],end=',')
stence="Whenever there's a problem,We'll be there on the double."
print(reverseOutputFirstword(stence))