python字符类型判断以及转换

1. 判断字符类型

s为一个字符串:
s.isalnum() 判断字符串否是数字字母
s.isalpha() 判断字符串是否为纯字母
s.isdigit() 判断字符串是否为纯数字
s.islower() 判断字符串中字母是否为纯小写字母(字符串中可以包含数字,返回为True)
s.isupper() 判断字符串中字母是否为纯大写字母(字符串中可以包含数字,返回为True)
s.isspace() 判断字符是否为空格,其中换行符(\n)、回车符(\r)、换页符(\f)均返回True
s.istitle() 判断字符串为纯字母,第一个字母是否为大写字母

s = "Life is short. I use python"
s_new = ''
count_upper = 0
count_lower = 0
count_digit = 0
count_space = 0
count_other = 0
print('原始数据:%s\n'%s)
for x in s:
	if(x.isupper()):
		count_upper += 1
	elif(x.islower()):
		x=x.upper()
		count_lower += 1
	elif(x.isdigit()):
		count_digit = count_digit + 1
	elif(x.isspace()):
		count_space = count_space + 1
	else:
		count_other = count_other + 1
	s_new = s_new + str(x)
#	print(x,end ="")
print("大写字母:{}个\n小写字母:{}\n数字个数:{}\n空格个数:{}\n其他个数:{}".format(count_upper,count_lower,count_digit,count_space,count_other))
print('\n大写数据:%s'%s_new)

print("\n## 判断首字符")
## 判断首字符
print('Abc'.istitle())## 是否是大写
print('abc'.istitle())
print('Abc'.isalpha())## 是否是字母
print('_bc'.isalpha())
## 判断字符串
print('##判断字符串')
print('mmdd22'.isalnum()) ## 是否是数字 或 字母
print('mm222222'.isdigit()) ## 是否是纯数字

在这里插入图片描述

2. 字符串转化

string = "you are a good man"

print(string.upper())          # 把所有字符中的小写字母转换成大写字母
print(string.lower())          # 把所有字符中的大写字母转换成小写字母
print(string.capitalize())     # 把第一个字母转化为大写字母,其余小写
print(string.title())          # 把每个单词的第一个字母转化为大写,其余小写

在这里插入图片描述


版权声明:本文为sinat_27691203原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。