首页 > 其他 > 详细

04基本数据类型---字符串

时间:2021-04-03 19:47:23      阅读:17      评论:0      收藏:0      [点我收藏+]

单双引号字符串是一样的,三重引号编写多行字符串块
用转义序列代表特殊字节:(\n换行、\\反斜杠、\t制表、\r回车、\"双引号)
raw字符串抑制转义

1、基本操作

#索引和切片
s = abc
print(len(s))
print(s[0:3:2]) 

# str转换int
s = 12
s = int(s)
s = str(s)

# str转换ascii码
print(ord(a)) # 97
print(chr(65)) # A

 2、字符串方法

strip()、lstrip()、rstrip() 去空格
join()

连接字符串

与‘+’的区别:‘+’每连接两个字符串就需要产生一个字符串,

join()是将所有字符串连接在一起后生成一个字符串 

split()、rsplit()、splitline() 分割和组合
find()、index() 查找
count() 统计子字符串出现次数
replace() 替换

startswith(str)、

endswith(str)、

isalnum()、

isalpha()、

isdigit()、

isspace()、

islow()、

isupper()、

istitle()

是否以str开头

是否以str结尾

是否全是字母和数字

是否全是字母

是否全是数字

是否全是空白字符

是否全是小写

是否全是大写

是否首字母大写

 

s = abc
s.replace(a,e)
print(s) #这时候结果依然是‘abc‘,因为str是不可变类型,不能在原处进行修改
s = s.replace(a,e) #对str重新赋值
print(s)

index = s.find(g) #S.find(sub[, start[, end]]) -> int,如果str不在 string中会返回-1。
print(index)
# print(s.index(‘g‘)) #S.index(sub[, start[, end]]) -> int,如果str不在 string中会报一个异常。

l = list(s)
print(l) # [‘e‘, ‘b‘, ‘c‘]

s = --.join(l) # S.join(iterable) -> str
print(s) #e--b--c

s = aa bb c
cols = s.split() # S.split(sep=None, maxsplit=-1) -> list of strings
print(cols) #[‘aa‘, ‘bb‘, ‘c‘]

s = aac\n   
s = s.rstrip() #S.rstrip([chars]) -> str 去除右边空白字符
print(s) #aac

s = hello cc
s = s.upper() #S.upper() -> str
print(s) #HELLO CC
print(s.upper()) #HELLO CC
print(s.isalpha()) #S.isalpha() -> bool
print(s.endswith(c)) #S.endswith(suffix[, start[, end]]) -> bool
print(s.startswith(a)) #S.startswith(prefix[, start[, end]]) -> bool

s = abc dea
print(s.count(a)) #S.count(sub[, start[, end]]) -> int

s = abc abc cc
print(s.capitalize()) #S.capitalize() -> str,字符串第一个字母大写,    Abc abc cc
print(s.title()) #S.title() -> str,字符串内的所有单词的首字母大写,     Abc Abc Cc

s = abc
print(s.isalnum()) #是否全是字母和数字
print(s.isalpha()) #是否全是字母
print(s.istitle()) #是否首字母大写
print(s.isspace()) #是否全是空白字符
print(s.isdigit()) #是否全是数字
print(s.isupper()) #是否全是大写
print(s.islower()) #是否全是小写

 

04基本数据类型---字符串

原文:https://www.cnblogs.com/cc-world/p/14613159.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!