Python 中的字符串

字符串常用属性和方法:

1.获取字符串长度

len( )函数: 获取字符串的长度

s =‘Python’

print(len(s))  # 6

2. 查找内容

find( ) 函数: 查找指定内容在字符串中是否存在,若存在则返回该内容在字符串中第一次出现的位置索引,不存在返回-1

s =‘This is a test OK, OK Or NOT’

print(s.find(‘OK’))

输出:15

print(s.find(‘OK’, 17))

输出: 19

print(s.find(‘PASS’))

输出:-1  (不存在,则返回-1)

3.判断字符串的开头和结尾

startswith(), endswith(): 判断字符串是否以某字符串开头或结尾

测试代码:

s =‘This is a test OK, OK Or NOT’

print(s.startswith(‘This’))

print(s.startswith(‘THIS’))

print(s.endswith(‘NOT’))

print(s.endswith(‘Not’))

输出:

True

False

True

False

4. 计算出现的次数

count()函数:计算某字符串在在字符串中出现的次数

测试代码:

s =‘AAAaaaBbbbCccc’

print(s.count(‘A’))

print(s.count(‘C’))

输出:

3

1

5.替换内容

replace( )函数:替换字符串中指定的内容,如果指定次数,则替换不超过指定次数

测试代码:

s =‘AAAaaaBbbbCccc’

print(s.replace(‘a’, ‘A’))

输出:

AAAAAABbbbCccc

print(s.replace(‘c’,‘A’))

输出:

AAAaaaBbbbCAAA

6. 切割字符串

split( )函数:通过参数的内容分隔字符串

测试代码:

s =‘1#3#5#8’

print(s.split(’#’))

输出:

[‘1’, ‘3’, ‘5’, ‘8’]

7.修改大小写

upper(),lower( )函数:字符串大小写转换

测试代码:

s =‘test’

print(s.upper())

print(s.lower())

输出:

TEST

test

8.空格处理

strip()函数: 去空格

测试代码:

s =’      space character strip     ’

print(’|’, s, ‘|’)

print(’|’, s.lstrip(), ‘|’)

print(’|’, s.rstrip(), ‘|’)

print(’|’, s.strip(), ‘|’)

输出:

|       space character strip     |

| space character strip       |

|       space character strip |

| space character strip |

lstrip函数去掉左边空格,l表示left, r表示right,当然是去掉右边空格,什么也不加的情况是去掉左右的空格。

9.字符串拼接

join() 函数:字符串拼接

测试代码:

s =’$’

print(s.join(‘Python’))

输出:

P y y yt h h ho$n

将字符插入搭配字符串的每个字符直接

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flysh05

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值