8 练习

#练习:
#请编写一个函数实现去掉字符串的头尾空格:
#如: trim(' hello') = 'hello'
#trim('hello ') = 'hello'
#trim('  hello world ') = 'hello world'
#trim('     hello world    ') = 'hello world'
def strJudge(str):
    #print(str.rfind(' '))
    print('input:{}'.format(str))
    if len(str) == 0:
        return "please input something"
    while str[0] == " ":
        str = str[1:]
        if len(str) == 0:
            return
    if len(str) == 0:
        return "nothing left"
    while str[-1] == " ":
        str = str[:-1]
        if len(str) == 0:
            break
    print("out: {}".format(str))
strJudge("       ")
strJudge("    sdf   ")
strJudge(" sdlkfj")
strJudge("sdlkfj.  ")
strJudge("")
---------------------------------------------
input:       
input:    sdf   
out: sdf
input: sdlkfj
out: sdlkfj
input:sdlkfj.  
out: sdlkfj.
input:
Out[9]:
'please input something'
#每个国家都有一定的地区号码, eg:+30希腊 +45丹麦 +51秘鲁 +65新加坡 +86中国
#写代码求出一下电话号码里面有几个国家:
# "+86 1123 +65 1234 +51 2347 +30 9123 +65 1246 +30 2347 +86 2935"
#python的高效率
str = "+86 1123 +65 1234 +51 2347 +30 9123 +65 1246 +30 2347 +86 2935"
print(str)
arrNew = str.split()
dic = {"+30":"希腊", "+45":"丹麦", "+51":"秘鲁", "+65":"新加坡", "+86": "中国"}
resultS = set([dic[item] for item in arrNew if item.startswith('+')])
print(resultS)
print(len(resultS))
--------------------------------------------------------------------------
+86 1123 +65 1234 +51 2347 +30 9123 +65 1246 +30 2347 +86 2935
{'中国', '秘鲁', '希腊', '新加坡'}
4

你可能感兴趣的:(8 练习)