前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python之字符串

Python之字符串

作者头像
py3study
发布2020-01-15 11:29:44
3580
发布2020-01-15 11:29:44
举报
文章被收录于专栏:python3python3
  • 字符串:比较常用的一种类型,通常也会结合正则表达式使用
    • 字符串操作 使用单引号、双引号、三引号(支持换行): str1='hello world' str2="hello python" print(str1,'\t',str2,'\n',type(str1),'\t',type(str2))
    • 字符串连接、重复 str1='hello world' str2="hello python" print(str1+str2) print(str1*3)
    Python之字符串
    Python之字符串
    • 索引访问操作 str1='hello world' str2="hello python" print(len(str1))#查看str1长度 print(str1[0:5])#前5个元素 print(str1[-1])#最后一个元素 print(str1[:-2])#除了最后两个元素 for i in str1: print(i,end=',')#以逗号间隔遍历元素
    Python之字符串
    Python之字符串
    • 异常操作:字符串属于不可变类型 print(str1[12]) #超出索引范围异常 print(str1[1]) str1[1]='1'
    Python之字符串
    Python之字符串
    • 字符串切片连接操作  split()会把字符串按照其中的空格进行分割,分割后的每一段都是一个新的字符串, 最终返回这些字符串组成一个list:split(),同时也会按照换行符\n,制表符\t进行分割,默认空白分割: 分片用法:string.split(self,sep,maxsplit)
    Python之字符串
    Python之字符串

     连接join操作:split是把一个字符串分割成很多字符串组成的list,而join则是把一个list中的所有字符串连接成一个字符串 用法:newstring='连接符号'.join(列表)

Python之字符串
Python之字符串
  • 字符串常用的操作方法:检查字符串index,find,count,endswith,去除特殊字符

s1='www.blog.51cto.com/blogger/draft/782804' #count检索指定字符串在另一个字符串中出现次数.如果检索的字符串不存在,则返回0 #用法str.count(self,x,__start,__end)可以指定范围 print(s1.count('w')) #统计’w'出现的次数 #index用法,返回首次出现的位置 print(s1.index('5')) #若不存在“ValueError: substring not found” #str.find(sub[, start[, end]]) 检索的字符串不存在,返回-1 , # 否则返回首次出现该子字符串时的索引 print(s1.find('5')) #endswith检索字符串是否以子字符串结尾,如果是就返回True,否则返回False print(s1.endswith('04')) strip操作: s1=' www.blog.51cto.com/blogger/draft/782804' s2='@hello python@.' print(s1) #str.strip(self,chars)去除首位空格或特殊字符 print(s1.strip()) print(s2.strip('@'+'.')) #+表示或的关系,首尾包含任一指定字符都将删除 #去除左边特殊字符str.lstrip(self,chars) print(s2.lstrip('@')) #去除右边特殊字符.rstrip() print(s2.rstrip('.'))

Python之字符串
Python之字符串

  • 简单使用
    • 注册会员 #假设已经 #将会员名称字符串全部转换为小写 # 通过手动输入要注册会员名称 # 将要注册的会员名称全部转换为小写 # 判断输入的会员名称是否存在,如果存在就提示已存在,如果不存在就以注册成功 # while True: # username_1="|Abc|mr|minsgiswoe|MRsoWDG|ew|" # username=username_1.lower() #转换为小写 # # print(username) # member=input('please input your registered name:') # # m=member.lower() #将输入的注册名字转换为小写 # m="|"+member.lower()+"|" #find和count方法纠正 # # if m in username.split('|'): # if username_1.find(m) != -1: #有缺陷只输入其中一部分也会匹配,显示已注册 # # if username.count(m) > 0: #与find一样 # 需限制范围 # print("sorry! name has Registered") # else: # username=username+''.join(member)+'|' # print("name register success.") # break # print(username)
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-06-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档