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.