• Count Words in a String


    class practiceYln():
        def __init__(self):
            self.text1 = None
            self.text2 = None
    
        def cwistr(self):
            text1 = input("please input a string:")
            text2 = input("please input a string you want to search in former string: ")
            count = text1.count(text2)  # 字符串的count方法
            if count > 1:
                count = str(count)  # int转换为str,否则无法进行后面的字符串拼接
                print(text2 +" showed " + count + " times in " + text1)
            else:
                count = str(count)
                print(text2 +" showed " + count + " times in " + text1)
    
    tt = practiceYln()
    tt.cwistr()
    
    #结果是:
    please input a string:baby
    please input a string you want to search in former string: b
    b showed 2 times in baby


    # 有没有更简洁的写法呢?当然!
    class practiceYln():
    def __init__(self):
    self.text1 = None
    self.text2 = None

    def cwistr(self):
    text1 = input("please input a string:")
    text2 = input("please input a string you want to search in former string: ")
    if text1.count(text2) > 1:
    print("%s showed %d times!" % (text2, text1.count(text2)))
    # 注意引用的文体: %s对应text2(字符型),%d对应text1.count(text2)(整数型)
    elif text1.count(text2) == 1:
    print("%s showed %d time!" % (text2, text1.count(text2)))
    else:
    print("string not included")

    tt = practiceYln()
    tt.cwistr()

    #结果是:
    please input a string:baby
    please input a string you want to search in former string: z
    string not included

    #别忘记python是面向对象的编程语言,所以我们可以调用已有的包实现这一功能
    from collections import Counter
    class practiceYln():
    def __init__(self):
    self.t1 = None
    self.t2 = None
    self.t3 = None
    self.t4 = None

    def cwistr(self):
    t1 = input("please input a string:")
    t2 = input("please input a string you want to search in former string: ")
    t3 = Counter(t1)
    t4 = str(t3[t2])
    print("the string showed " + t4 + " times.")

    tt = practiceYln()
    tt.cwistr()

    # 结果是:
    please input a string:Robert
    please input a string you want to search in former string: r
    the string showed 1 times.



    May we all proceed with wisdom and grace. https://www.cnblogs.com/YlnChen/
  • 相关阅读:
    java.lang.IllegalAccessError: tried to access field org.slf4j.impl.StaticLoggerBinder.SINGLETON from class org.slf4j.LoggerFactory
    项目开发中关于权限的实现方案简单描述(帮助以后回忆)
    一些比较有用的模板
    递归之遍历部门
    关于s2sh框架关于hibernate懒加载问题的说明和解决方案
    Hibernate实体映射配置(XML)简单三步完美配置
    项目添加性能监控日志
    redis常用命令大全
    redis主从同步
    redis之哨兵部署运行日志解读
  • 原文地址:https://www.cnblogs.com/YlnChen/p/12581535.html
Copyright © 2020-2023  润新知