zoukankan      html  css  js  c++  java
  • 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/
  • 相关阅读:
    MySQ随笔2(连接表、分组)
    MySQL随笔
    Python随笔1
    要学习但还没学的知识点2016年8月4号
    jQuery备忘录--私家版
    Chrome 中的彩蛋——T-Rex
    JavaScript多线程初步学习
    实例:jQuery实现标签切换
    实例:用jQuery实现垂直和水平下拉 菜单
    AJAX编程模板
  • 原文地址:https://www.cnblogs.com/YlnChen/p/12581535.html
Copyright © 2011-2022 走看看