字符串判断大小及开头结尾的匹配

判断字符串里每个元素是否为 什么类型,一旦有一个元素不满足,就返回False

print('123'.isdigit())
print('123hello'.isdigit())

打印结果:返回的值为布尔值,只有两个结果,True and False
True
False

title:标题 判断某个字符串是否为标题(第一个字母大写,其余字母小写)

print('hello'.istitle())  False       判断hello是否开头第一个字母为大写的标题
print('Hello'.istitle())  True        判断Hello是否为标题


print('hello'.isupper())  False        判断hello是否为大写
print('Hello'.upper())    HELLO        将hello大写输出
print('HELLO'.lower())    hello        将HELLO小写输出
print('HELLO'.islower())  False        判断HELLO是否为小写


print('hello123'.isalnum()) True       判断hello123是否为字母和数字的组合
print('123'.isalpha())      False      判断123是否字母
print('qqq'.isalpha())      True       判断qqq是否为字母

字符串的开头结尾匹配:

开头匹配:startswith

url1 = 'file:///mnt'
url2 = 'ftp://172.25.254.250/pub'
url3 = 'https://172.25.254.250/index.html'

if url3.startswith('http://'):
    print('网页获取成功')
else:
    print('未找到网页')


运行结果:
未找到网页

结尾匹配:endswith

filename = 'hello.loggg'

if filename.endswith('.log'):
    print(filename)
else:
    print('error filename')


运行结果:
error filename

删除左右空格:

In [1]: s = '      hello      '                                         

In [2]: s                                                               
Out[2]: '      hello      '        输出的两边都有空格

In [3]: s.strip()                  去除空格显示                       
Out[3]: 'hello'

In [4]: s.rstrip()                 去除右边的空格                           
Out[4]: '      hello'

In [5]: s.lstrip()                 去除左边的空格                          
Out[5]: 'hello      '

删除特定的字母

a = '\nhello\t\t'        \n为换行,\t为一个tab键
print(a)

运行结果:

hello		
                   

In [8]: s = 'helloh'
In [9]: s.strip('h')          去掉s 中h元素        
Out[9]: 'ello'            
In [11]: s.lstrip('he')       去掉s的 he元素
Out[11]: 'lloh'

猜你喜欢

转载自blog.csdn.net/weixin_43323669/article/details/86519377