zoukankan      html  css  js  c++  java
  • 0503---练习题 punctuation isdigit() strip() upper()

    #习题1:一个句子中的所有数字和标点符号删除

    def delete_num_punctuation(s):
        import string
        for i in s:
            if i in string.punctuation:#判断是否有标点,是的话替换掉
                s=s.replace(i," ")
        s=s.split()
        result =[]
        for i in s:
            if not i.isdigit():#用isdigit函数判断是否数字
                result.append(i)
        return " ".join(result)

    s
    ="I am 15 years old!" print(delete_num_punctuation(s))

     C:Usersdell>py -3 C:UsersdellDesktop练习5503.py
    I am years old

    代码优化:

    #上述代码两次遍历字符串,可以优化写在一起,最后直接拼接

    s="I am 15 years old!"
    def delete_num_punctuation(s):
        import string
        str =""
        for i in s:
            if not i.isdigit() and i not in string.punctuation:
                str +=i
        return str
    
    print(delete_num_punctuation(s))

    #习题2:自定义实现strip()
    Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
    注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
    strip()方法语法:
    str.strip([chars])

    s=" abc  d 
    "
    result =""
    for i in s:
        if i not in ["
    ","
    ","	"," "]:
            result +=i
    
    print(result)

    #习题3:自定义实现str.upper()

    Python upper() 方法将字符串中的小写字母转为大写字母。

    upper()方法语法:

    str.upper()
    s="hdka"
    str_result =""
    for i in s:
            if i>=chr(ord('a')) and i<=chr(ord('z')):
                str_result +=chr(ord(i)-32)
            else:
                str_result +=i
    print(str_result)
    #习题4:自定义实现str.lower()
    s="FHSJKakaae"
    str_result =""
    for i in s:
            if i>=chr(ord('A')) and i<=chr(ord('Z')):
                str_result +=chr(ord(i)+32)
            else:
                str_result +=i
    print(str_result)
  • 相关阅读:
    LeetCode 1672. 最富有客户的资产总量
    LeetCode 455. 分发饼干
    Linux上安装docker并设置免sudo权限与国内镜像源
    Java后端期末复习
    Windows 10 家庭版开启本地安全策略 关闭管理员权限提升
    C语言中两种交换变量值方法的速度测试
    jQuery动态生成元素无法绑定事件的解决办法
    JQuery绑定事件处理动态添加的元素
    Socket通信服务端和客户端总结
    js传函数指针
  • 原文地址:https://www.cnblogs.com/wenm1128/p/10805378.html
Copyright © 2011-2022 走看看