Python基础-字符串实例

本文介绍了Python的基础知识,包括字符串操作、真假值判断、基本数据类型的使用方法。通过实例演示了字符串的大小写转换、填充位置调整、字符统计等功能,以及如何进行数字的转换和计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

字符串判断

详细列表参考博文《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

转载于:https://my.oschina.net/zhaojunhui/blog/1790551

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值