python字符串介绍_python字符串详解

必选掌握

#isupper判断字符串是否全部都是大写

str1 = 'Hello,world'

str2 = 'HELLO,WORLD'

print(str1.isupper()) False

print(str2.isupper()) True

#islower判断字符串是否全部都是小写

str1 = 'Hello,world'

str2 = 'hello,world'

print(str1.islower()) False

print(str2.islower()) True

#isalnum判断字符串里是否有数字、字母、汉字.(或判断字符串里是否有特殊字符)

str1 = '11122333aaah郝'

str2 = '11122333/qaaa'

print(str1.isalnum()) True

print(str2.isalnum()) false

#isdigit判断字符串里面是否是整型

str1 = '123'

print(str1.isdigit())

True

#upper()方法把字符串全部变成大写

str = 'Hello,World'

print(str.upper())

HELLO,WORLD

#startswith判断字符串开头是否为He

print(str1.startswith('He'))

#endswith判断字符串结尾是否为ld

print(str1.endswith('ld'))

#index取字符串o的下标,如果没有这个字符会报错

str1 = 'Hello,World'

print(str1.index('o'))

4

print(str1.rindex('o'))

7

#find取字符串o的下标,如果没有这个字符返回-1

str1 = 'Hello,World'

print(str1.find('o'))

4

print(str1.rfind('o'))

7

print(str1.find('y'))

-1

#isalpha判断字符串里是英文或汉字

str1 = 'Hello,World'

print(str1.isalpha())

false

#count统计字符串里l字符的个数

print(str1.count('l'))

3

#istitle判断是否是抬头

抬头判断标准:连续不间断单词首字母大写,其余为小写,否则为false

print(str1.istitle())

True

#把一个字符串变成抬头

print(str1.title())

#isspace判断字符串是否是纯空格

str1 = ''"

str2 = '' "

print(str1.isspace())

false

print(str2.isspace())

Ture

# replace替换字符串o成sb,并且只替换1次

str1 = 'Hello,world'

res = str1.replace('o','sb',1)

print(res)

Hellsb,world

#把一个可迭代对象(列表,元组,集合,字典,字符串)变成字符串,表中数据类型为字符串

res = ''.join(['abc','123','吉喆'])

print(res)

print(type(res))

abc123吉喆

# str1 = '192.168.250.250'

把一个字符串从左往右切分变成列表(.代表切分点,1代表切分1次)

res = str1.split('.',1)

print(res)

['192', '168.250.250']

#把一个字符串从右往左切分变成列表(.代表切分点,1代表切分1次)

res = str1.rsplit('.',1)

print(res)

['192.168.250', '250']

#去除字符串左右两边指定的字符(注意:必须为两边边界)

str1 = '++++++Hello,World====='

res = str1.strip('=')

print(res)

++++++Hello,World

print(str1.strip('+'))

Hello,World=====

#去除字符串右边指定的字符

res = str1.rstrip('=')

print(res)

#去除字符串左边指定的字符

str1.lstrip('+')

#format将字符串格式化,可以有以下3种格式

str1 = 'my name is {},my age is {}'

res = str1.format('吉喆', '23')

str1 = 'my name is {1},my age is {0}'

res = str1.format('23', '李凯')

str1 = 'my name is {name},my age is {age}'

res = str1.format(name='李凯', age='23')

print(res)

#%s,%d,%f可以格式化字符串

str1 = 'my name is %s, my age is %s'

res = str1 % ('吉喆', 23)

print(res)

my name. is 吉喆, my age is 23

#利用索引或者下标取值,超出范围报错

str1 = 'Hello,World'

print(str1[-100])

#字符串的拼接

print(str1[4]+str1[5])

o,

print('1'+'2')

12

#切片

str1 = 'Hello,World'

res = str1[2:5]#正向切片顾头不顾尾

print(res)

llo

# res = str1[-4:-1]#顾尾不顾头

print(res)

rld

# res = str1[:3]#索引为3往右的字符不要了(包括下标为3的字符)

print(res)

Hel

# res = str1[3:]#索引为3往左的字符不要了(不包括下标为3的字符)

print(res)

lo,World

# res = str1[::2]#步长为2,隔一个字符取一个字符

print(res)

HloWrd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值