栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python str常用方法(1)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python str常用方法(1)

文章目录
    • 1.字符串常用方法
        • 1.1 获取长度:len
        • 1.2 查找内容:find
        • 1.3 判断: startswith,endswith  
        • 1.4 计算出现次数:count
        • 1.5 替换内容:replace
        • 1.6 切割字符串:split
        • 1.7 修改大小写:upper,lower
        • 1.8 字符处理: 去空格、去字符

1.字符串常用方法 1.1 获取长度:len

len函数可以获取字符串的长度。

str1 = 'hello world'
# len 获取长度
print(len(str1))  # 输出为11
1.2 查找内容:find

查找指定内容在字符串中是否存在,如果存在就返回该内容在字符串中第一次 出现的开始位置索引值,如果不存在,则返回-1。

str1 = 'hello world'
print(str1.find('ld'))  # 输出为9
1.3 判断: startswith,endswith  

判断字符串以指定str开头或结尾

str1 = 'hello world'
print(str1.startswith('helo'))  # False
print(str1.endswith('ld'))  # True
1.4 计算出现次数:count

返回 str在start和end之间 在 mystr里面出现的次数

str.count(被查找字符串,起始位置,结束位置)
str1 = 'hello world'
print(str1.count('l'))  # 3
print(str1.count('lsp'))  # 0
print(str1.count('l', 1, 3))  # 1
1.5 替换内容:replace

替换字符串中指定的内容,如果指定次数count,则替换不会超过count次。
不过貌似并不会修改原字符串的值

str1 = 'hello world'
print(str1.replace('hello', 'hi'))  # hi world
print(str1.replace('l', 'Q', 2))  # heQQo world
print(str1)  # hello world,替换了几次str1还是原来的值
1.6 切割字符串:split

通过参数的内容切割字符串

str.split(分隔符,最大分割次数)

str2 = "taobao#huawei#xiaomi#jingdong"
print(str2.split('#'))  # ['taobao', 'huawei', 'xiaomi', 'jingdong']
print(str2.split('#', 1))  # ['taobao', 'huawei#xiaomi#jingdong']
1.7 修改大小写:upper,lower

将字符串中的大小写互换

str1 = 'hello world'
print(str1.upper())
print(str1.upper().upper())
print('HELLO'.lower())
1.8 字符处理: 去空格、去字符

1.strip 同时去掉左右两边的字符
2.lstrip 去掉左边的字符
3.rstrip 去掉右边的空格

用法:  str.strip(s)
s为要删除的内容

str2 = ' 123 456 '
print('原字符:     **' + str2 + '**')
print('删除两头空格:**' + str2.strip() + '**')
print('删除左空格:  **' + str2.lstrip() + '**')
print('删除右空格:  **' + str2.rstrip() + '**')
str3 = '123454321'
print('删除 12:' + str3.strip('12'))

输出结果:

原字符:     ** 123 456 **
删除两头空格:**123 456**
删除左空格:  **123 456 **
删除右空格:  ** 123 456**
删除 12:34543

####1.9 字符串拼接:join

str1 = '!'
str2 = 'hello world'
print(str1.join(str2))  # h!e!l!l!o

输出结果:

h!e!l!l!o! !w!o!r!l!d
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/875484.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号