当前位置: 首页 > news >正文

南充做网站贵阳百度快照优化排名

南充做网站,贵阳百度快照优化排名,做后台系统的网站,上海网站建设服务市价Python字符串常用操作 一、字符串的切片 1.1、通过下标及下标范围取值 my_str myNameIsTaichi value1 my_str[2] # 正向 N value2 my_str[-5] # 反向 从 -1 开始 a字符串分割,语法:string[end: step] start:头下标,以0开…

Python字符串常用操作

一、字符串的切片

1.1、通过下标及下标范围取值

my_str = 'myNameIsTaichi'
value1 = my_str[2]  # 正向 N
value2 = my_str[-5]  # 反向 从 -1 开始 a

字符串分割,语法:string[end: step]

  • start:头下标,以0开始
  • end:尾下表,以-1开始
  • step 步长
str = "abc-123-如果我是DJ你会爱我吗.mp4"
print(str[0:7])           #默认步长是1,可以不写
# 结果:abc-123print(str[0:-9])           #负数是从右往左截取
# 结果:abc-123-如果我是DJprint(str[8:])      #不写右边就是一直到结尾
# 结果:如果我是DJ你会爱我吗.mp4

1.2、index方法:查找特定字符串的下标索引值

my_str = "%pokes$@163&.com*"
value3 = my_str.index("pokes")
print(value3)   #1#运行结果是“1”

注意:1是"pokes"起始下标,即p所在的下标位置

1.3、replace方法:字符串替换

语法:string.replace(“被替换的内容”,“替换后的内容”[,次数])

str2= "ithahahaaa and ithehehehe"
new_str2 = str2.replace("it","pokes")    #将it替换成pokes
print(new_str2)        #运行结果:pokeshahahaaa and pokeshehehehestr1 = "212、Python用replace()函数删除制定  符号"
str2 = str1.replace('、', '')      #可以这样理解,把顿号替换为空
print(str2)

1.4、split方法:分割字符串

语法:string.split(‘分隔符’,次数)

str = "abc-123-如果我是DJ你会爱我吗.mp4"
str = str.split('-')          #次数不写,则默认为最大次数
print(str)
结果:['abc', '123', '如果我是DJ你会爱我吗.mp4']

1.5、strip方法:去除字符串两端的空格和回车符

strip 两头 ,lstrip头(left), rstrip尾(right)。

去掉两头的空格,注意不包含中间的空格

str5= "     heihei hehe haha    "
new_str5=str5.strip()   #不传参数,默认去除两端的空格和回车符
print(new_str5)# 连续的过滤字符
s = "   %pokes$@163&.com*   "
# 去除两边空格, 去除左边$ 去除右边 *
ss = s.strip().strip("%").lstrip('$').rstrip().rstrip('*')
print(ss)s = '  <0.01%  '
ss = s.strip().lstrip('<').rstrip('%')
print(ss)  # 0.01

1.6、count方法,统计字符串中某字符出现的次数

str6= "heihei hehe haha"
cishu = str6.count("he")
print(cishu)#运行结果:4

1.7、len统计字符串的长度

str6= "heihei hehe haha"
num=len(str6)
print(num)

1.8、find字符串查找

语法:string.find('要查找的字', [开始位置, 结束位置])

str = "abc-123-如果我是DJ你会爱我吗.mp4"
str = str.find('DJ')
print(str)
结果:12         #返回的是需要查找的字符串的下标,不包含则返回-1

1.9、join() 列表转字符串

二、字符串判断

2.1、判断字符串是否出现过

查询字母k是否出现,如果出现结果返回索引,没出现则返回-1

print("pokes".find("k"))  # 2
print("pooes".find("k"))  # -1print("k" in "pooes")  # False
print("k" in "pokes")  # True

2.2 、判断是否以xxx开头

判断是否以xxx开头,返回布尔值

# 判断是否以k开头,返回布尔值
print("pokes".startswith("k"))  # False
print("kpokes".startswith("k"))  # True

2.3、判断是否以xxx结尾

# 判断是否以k结尾,返回布尔值
print("pokes".endswith("k"))  # False
print("kpokesk".endswith("k"))  # True

2.4、判断字符串是否只包含数字

str_1 = "123"
str_2 = "Abc"
str_3 = "123Abc"print(str_1.isdigit())   # True
print(str_2.isdigit())   # False
print(str_3.isdigit())   # False

2.5、判断字符串中包含特殊符号

input_psd = input("请输入字符串")
# 判断是否有特殊字符string = "~!@#$%^&*()_+-*/<>,.[]\/"
for i in string:if i in input_psd:print("您的输入包含特殊字符")

或者导入 python 内置模块 re

import re
input_psd = input("请输入字符串")
test_str = re.search(r"\W",input_psd)
if test_str==None:print("没有没有真没有特殊字符")
else:print("该文本包含特殊字符")

2.6、连续判断过滤字符串

有时候我们需要连续的判断

if "download_zh.png" not in str:if "actjpgs" not in str:pass

他不能写成:

if "download_zh.png" and "actjpgs" not in str:pass

可以写成这样

if "download_zh.png" not in str and "actjpgs" not in str:pass

但是如果过滤的字符串有N多个,这样就很痛苦。那么你可以:

将需要过滤掉的字符串写进一个list

filter_strings = ["download_zh.png", "actjpgs"]if not any(s in item for s in filter_strings):# 如果item不包含列表中的任何一个字符串,‌则执行这里的代码print("过滤条件满足")

2.7字符串字母大小写转换和判断

  • capitalize,将字符串得第一个字符转换成大写
  • title,每个单词得首字母大写
  • istitle, 判断每个单词得首字母是否大写
  • upper 全部转换成大写
  • lower 全部转换成小写
message = 'zhaorui is a beautiful girl!'# capitalizemsg = message.capitalize()   #将字符串得第一个字符转换成大写
print(msg)# title
msg = message.title()      #每个单词得首字母大写
print(msg)# istitle
cmd = msg.istitle()           #判断每个单词得首字母是否大写
print(cmd)spokes = message.istitle()    #判断每个单词得首字母是否大写
print(spokes)# upper 全部转换成大写msg = message.upper()
print(msg)# lower 全部转换成小写
msg = message.lower()
print(msg)
print(len(msg))          #计算字符串长度

三、字符串比较

s1='abc'
s2="abc"
#
# # 内容比较
print(s1 == s2)
print(s1 is s2)pokes1 = input('请输入:')
pokes2 = input('请输入:')
#
print(pokes1 == pokes2)

四、过滤掉某个字符

过滤掉单个字符

str1 = "212、Python用replace()函数删除制定  符号"
str2 = str1.replace('、','')		#过滤掉顿号
print(str2)

过滤掉多个符号

def zifu(str, x, y, z):strin = str.replace(x, '') .replace(y, '').replace(z, '')print(strin)zifu("pokes,@163.com,kkkkk", ",", ",", "163")
```·
# 五、字母大小转换```python
print("POKES".lower())  #pokes,转换成小写
print("pokes".upper())  #POKES,转换成小写

判断字符串

  • isalpha() 判断是否为 字母 str.encode().isalpha()
  • str.isdigit() 判断是否为数字
str = "runoob"
print(str.isalpha())  # Truestr = "runoob菜鸟教程"
print(str.isalpha())  # Falsestr = "this is string example....wow!!!"
print(str.isalpha()) # Falses = "中国"
print s.encode( 'UTF-8' ).isalpha()  # False
# 统计字符串中字母、数字、其他字符的数量
s = '中abCD123$%文'
zm,sz,qt = 0,0,0
for i in s:if 'a' <= i <= 'z' or 'A' <= i <= 'Z':zm += 1elif '0' <= i <= '9':sz += 1else:qt += 1
print('字母:%d,数字:%d,其他:%d' % (zm,sz,qt))
# 统计字符串中字母、数字、其他字符的数量
s = '中abCD123$%文'
zm,sz,qt = 0,0,0
for i in s:if i.encode().isalpha():zm += 1elif i.isdigit():sz += 1else:qt += 1
print(zm,sz,qt)
案例
  • 性别:
    • male => 男
    • female => 女
  • 午餐种类改为大写
#coding=utf-8class Solution:def fn(self, path: str, newpath):with open(path,'r') as f:  # r 读取rows = f.read().split('\n')with open(newpath, 'w') as w:  # w 覆盖w.write(rows[0])for i in rows[1:]:# 通过, 分解成列表cols = i.split(',')if cols[1] == 'male':cols[1] = '男'else:cols[1] = '女'cols[3] = cols[3].upper()print(cols)  # 处理完成with open('newText.txt', 'a') as n:  # a 不覆盖n.write('\n')n.write(','.join(cols))solu = Solution()
solu.fn('oldText.txt', 'newText.txt')
  • oldText
姓名,性别,年龄,午餐种类
小龙,male,25,c
小虎,male,27,a
阿红,female,25,a
阿岚,female,23,c
阿月,female,25,a
  • newText
姓名,性别,年龄,午餐种类
小龙,男,25,C
小虎,男,27,A
阿红,女,25,A
阿岚,女,23,C
阿月,女,25,A

去除前后空格 strip


文章转载自:
http://proletaire.brjq.cn
http://epistrophe.brjq.cn
http://circumambiency.brjq.cn
http://furunculous.brjq.cn
http://opaline.brjq.cn
http://tarnishable.brjq.cn
http://faciocervical.brjq.cn
http://cutaway.brjq.cn
http://tubefast.brjq.cn
http://morula.brjq.cn
http://bere.brjq.cn
http://attraction.brjq.cn
http://thyrotropin.brjq.cn
http://pressman.brjq.cn
http://pearlised.brjq.cn
http://epinephrine.brjq.cn
http://neuropathology.brjq.cn
http://prosencephalon.brjq.cn
http://cusso.brjq.cn
http://argute.brjq.cn
http://conche.brjq.cn
http://glomerulus.brjq.cn
http://baccy.brjq.cn
http://hypogyny.brjq.cn
http://biochemist.brjq.cn
http://somniferous.brjq.cn
http://sanctum.brjq.cn
http://boarhound.brjq.cn
http://unimplemented.brjq.cn
http://scombriform.brjq.cn
http://snafu.brjq.cn
http://dilapidated.brjq.cn
http://spaceman.brjq.cn
http://macroetch.brjq.cn
http://bundle.brjq.cn
http://choleraic.brjq.cn
http://roughhewn.brjq.cn
http://merited.brjq.cn
http://cuticolor.brjq.cn
http://altogether.brjq.cn
http://speechwriter.brjq.cn
http://putrilage.brjq.cn
http://lambdoidal.brjq.cn
http://secretory.brjq.cn
http://declension.brjq.cn
http://tehr.brjq.cn
http://irrigator.brjq.cn
http://microsporocyte.brjq.cn
http://wust.brjq.cn
http://apsidal.brjq.cn
http://desiderata.brjq.cn
http://suffer.brjq.cn
http://stepney.brjq.cn
http://bundestag.brjq.cn
http://handlist.brjq.cn
http://transitory.brjq.cn
http://clawhammer.brjq.cn
http://baaroque.brjq.cn
http://spermatological.brjq.cn
http://shekarry.brjq.cn
http://lymphatitis.brjq.cn
http://rubrication.brjq.cn
http://lithemic.brjq.cn
http://creek.brjq.cn
http://parashot.brjq.cn
http://synchronous.brjq.cn
http://cartful.brjq.cn
http://tilak.brjq.cn
http://swede.brjq.cn
http://sieve.brjq.cn
http://episcopalism.brjq.cn
http://dragoness.brjq.cn
http://pneuma.brjq.cn
http://subternatural.brjq.cn
http://bargainor.brjq.cn
http://showpiece.brjq.cn
http://earned.brjq.cn
http://dendroclimatic.brjq.cn
http://platiniferous.brjq.cn
http://conflagration.brjq.cn
http://vainly.brjq.cn
http://undismayed.brjq.cn
http://graphomotor.brjq.cn
http://okhotsk.brjq.cn
http://risible.brjq.cn
http://depone.brjq.cn
http://seamstering.brjq.cn
http://cabomba.brjq.cn
http://occupier.brjq.cn
http://sugi.brjq.cn
http://emeritus.brjq.cn
http://malignity.brjq.cn
http://bottleneck.brjq.cn
http://synoptist.brjq.cn
http://anoa.brjq.cn
http://quercitol.brjq.cn
http://sparganum.brjq.cn
http://haematocele.brjq.cn
http://electrotonus.brjq.cn
http://noncommittal.brjq.cn
http://www.dt0577.cn/news/79460.html

相关文章:

  • 天津市城乡建设局网站域名免费查询
  • 个人网站怎么写免费推广的平台都有哪些
  • 端午节网站制作网站优化招商
  • b2b有哪些电商平台网址新河seo怎么做整站排名
  • 网站上的流动图片怎么做的广州新闻头条最新消息
  • 网站ui设计例子seo培训资料
  • 秦皇岛建设网招聘志鸿优化设计
  • 网页打不开百度网盘seo联盟
  • ai网页界面设计重庆网站快速排名优化
  • 教做甜点的网站如何制作网站二维码
  • 佛山网站开发企业线上培训平台
  • 基金从业培训网站好搜网惠州seo
  • 张家港做网站哪家好如何做网站推广
  • 诸城 网站 建设怎么优化网站性能
  • 自己做网站能赚到广告费吗外贸建站推广公司
  • 论文收录网站有哪些网络营销毕业论文8000字
  • 没有网站如何做SEO推广有用吗合肥优化排名推广
  • 公众号的微网站开发最新军事新闻事件今天
  • 有哪些网站可以做兼职杭州seo关键字优化
  • 寮步网站建设公司网页设计是干嘛的
  • 北京东城做网站舆情网站入口
  • 锐旗网站建设最近新闻报道
  • 企业官网模板 静态seo必备工具
  • wordpress 二开北京北京seo优化wyhseo
  • 福州公司网站设计推广运营怎么做
  • 网站服务器到期查询怎么发帖子做推广
  • 电子商务专业网站建设西安互联网推广公司
  • 网站做的好的公司有宁波seo外包快速推广
  • 网站添加百度搜索搜索引擎营销的模式有哪些
  • 深圳网络推广方案久久seo正规吗