字符串判断
详细列表参考博文《Python基础-运算》
判断字符“小”是否在字符串“小明”中
name = "字符串"
if "字符" in name:
print("字符在字符串中!")
else:
print("字符不在字符串中")
if "字符" not in name:
print("字符不在字符串中!")
else:
print("字符在字符串中!")
真假值判断
if '真' == '真' and '真的' == '真的' or "真的" == "假的" and "假的" == '假的':
print("结果为true")
else:
print("结果为false")
基本数据类型
参考笔记《Python参考手册-方法》
数字(int)
python2中分整型和长整型
方法示例
将字符串“123”转换为Int并输出计算后类型和计算结果
a = "123"
b = int(a)
c = 456
d = b + c
print(type(d))
print(d)
将数字“11001”以二进制方式计算的值换算成十进制,并用 方法:bit_length() 输出二进制位数
num = "11001"
v = int(num,base=2)
print(v)
z = v.bit_length()
print(z)
字符串(str)
大小写切换
首字母大写,其它小写
a = "TExt"
m = a.capitalize()
print(m)
字母小写处理,lower不能转换字符或者其它国家语言等,常用的是casefold
a = "TExt"
n = a.casefold()
print(n)
或
n2 = a.lower()
print(n2)
字母大写处理
a = "TExt"
o = a.upper()
print(o)
大小写互换
test = "ABcd"
v = test.swapcase()
print(v)
字符串填充位置调整
字符串居中,靠左,靠右
test = "字符"
v1 = test.center(20,"*")
print(v1)
v2 = test.ljust(20,"*")
print(v2)
v3 = test.rjust(20,"*")
print(v3)
*********字符*********
字符******************
******************字符
统计字符出现次数
test = "1232354"
v = test.count("2")
print(v)
从字符串中寻找子数列出现次数
test = "abcdefgabcdefgabc"
v = test.count("b",2)
print(v)
字符串结尾判断(startswith)相反
test = "abc"
x = test.endswith('c')
print(x)
True
y = test.endswith('bc')
print(y)
True
z = test.endswith('b')
print(z)
False
字符串格式化-占位符替换传值
test = 'I am {a}'
v = test.format(a='小明')
print(v)
I am 小明
test = 'I am {0},age {1}'
v = test.format('小明','15')
print(v)
字符串查找,并定位。无内容find返回-1,index报错
test = "xiaoming"
v = test.find('m')
print(v)
v2 = test.index('m')
print(v2)
判断字符串是否只有数字和字母
test = "sdaf22@"
v = test.isalnum()
print(v)
判断字符串是否为字母
test = 'abc'
v = test.isalpha()
print(v)
判断字符串是否为数字
test = '123'
v1 = test.isdecimal()
v2 = test.isdigit()
print(v1,v2)
True True
test = '②'
v1 = test.isdecimal()
v2 = test.isdigit()
print(v1,v2)
False True