9.python基础学习-小程序演练-99乘法表、字符串去空格、判断字符串是否有空格、字符串以xx开头/结尾

修订日期 内容
2021-2-14 ① 99乘法表
②判断字符串是否有空格
③字符串去空格
④字符串以xx开头/结尾判断
2021-2-15 修改命名规范,增加是否空字符串判断

9.python基础学习-小程序演练-99乘法表、字符串去空格、判断字符串是否有空格、字符串以xx开头/结尾判断

99乘法表

# 实现一个9*9乘法表

for i in range(1, 10):
    for j in range(1, i+1):
        print('{0}*{1}={2}'.format(j, i, i * j),end='\t')
    print()
    
'''
1*1=1	
1*2=2	2*2=4	
1*3=3	2*3=6	3*3=9	
1*4=4	2*4=8	3*4=12	4*4=16	
1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	
1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36	
1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49	
1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64	
1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81	
'''

判断字符串是否有空格

def hasempty(s):
    return s.find(' ') != -1

# 测试
print(hasempty('你这的有空格 吗?'))  # True
print(hasempty(' 你这的有空格 吗?'))  # True
print(hasempty('你这的有空格吗? '))  # True
print(hasempty('  你这的有空格吗? '))  # True
print(hasempty('没有空格!'))  # False

字符串去空格

# 去空格
def trim(s):
    return s.replace(' ', '')

print(trim(' 有空 格 '))  #有空格

字符串是否以xx开始

# 判断字符串以什么开头,以什么结尾
def start_with(s,start):
    return s.find(start,0,len(start)) == 0


print(start_with('python','p'))   # True
print(start_with('python','py'))  # True
print(start_with('python','on'))  # False

字符串是否以xx结尾

def end_with(s,end):
    rindex = s.rfind(end)
    return rindex != -1 and rindex >= len(s) - len(end)


print(end_with('java', 'java'))  # True
print(end_with('java', 'a'))  # True
print(end_with('java', 'va'))  # True
print(end_with('java', 'p'))  # False
print(end_with('java', 'pa'))  # False
print(end_with('java', 'javajava'))  # False

判断是否空字符串

def is_empty(s):
	return isinstance(s,str) and not s
print(is_empty(''))  # True
print(is_empty(' '))  # False

Guess you like

Origin blog.csdn.net/weixin_48470176/article/details/113808405