python数据类型之str用法
1、首字母大写
语法:S.capitalize() -> str title = "today is a good day"
title_ca = title.capitalize()
print(title_ca) 结果:today is a good day
2、大写转小写
语法:S.casefold() -> str title = "TODAY is a GOOD day"
title_ca = title.casefold()
print(title_ca) 结果:Today is a good day
3、字符串居中
c = 'kong' ret = c.center(,'*')
print(ret) 结果:***kong***
4、字符串子串数量统计
S.count(sub[, start[, end]]) -> int title = "today is a good day"
title_ca = title.count('y',,)
print(title_ca) 结果:
5、中文转UTF-8
S.encode(encoding='utf-8', errors='strict') -> bytes zw = '孔扎根'
ut = zw.encode()
print(ut) 结果:b'\xe7\xa9\xba\xe6\x89\x8e\xe6\xa0\xb9'
6、字符串结束判断
S.endswith(suffix[, start[, end]]) -> bool title = "TODAY is a GOOD day"
title_ca = title.endswith('day')
print(title_ca) 结果:True
7、TAB转空格
S.expandtabs(tabsize=) -> str
#默认是一个TAB转8个空格
title = "TODAY\tis\ta\tGOOD\tday"
title_ca = title.expandtabs()
print(title_ca) 结果:TODAY is a GOOD day
8、查找字符串的位置
S.find(sub[, start[, end]]) -> int title = "TODAY\tis\ta\tGOOD\tday"
title_ca = title.find('s')
print(title_ca) 结果:
9、字符串格式化
S.format(*args, **kwargs) -> str
#可传入元组或字典
title = "{}\tis\ta\t{day_type}\tday"
title_ca = title.format('TODAY',day_type='GOOD')
print(title_ca) 结果:TODAY is a GOOD day
10、字符串格式化,从字典输入(format_map)
S.format_map(mapping) -> str
#输入参数为字典,循环读字典中的列表
maping_name = {
'name':['alex','join'],
'age':[,]
} for x in range():
print('my name is {},and i is {} old'.format(maping_name['name'][x],maping_name['age'][x])) 结果:
my name is alex,and i is old
my name is join,and i is old
11、字符串的索引位置
S.index(sub[, start[, end]]) -> int
#查找Y的索引位置,从0开始数
title = "TODAY\tis\ta\tGOOD\tday"
title_ca = title.index('Y')
print(title_ca) 结果:
12、字符串中至少有一个数字
S.isalnum() -> bool
#字符串不能有空格,否则失败
title = "22TODAY"
title_ca = title.isalnum()
print(title_ca) 结果:True
13、字符串中至少有一个字母
S.isalpha() -> bool
#字符串不能有空格或TAB键
title = "22TODAY"
title_ca = title.isalnum()
print(title_ca) 结果:True
14、字符串是否为数值
num = "" #unioncode
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
True
True
True num = "1"#全角
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
True
True
True num = b""#byte
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
True
AttributeError: 'bytes' object has no attribute 'isdecimal'
AttributeError: 'bytes' object has no attribute 'isnumeric' num = "IV"#罗马字符
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
False
False
False num = "四"#汉字
print(num.isdigit())
print(num.isdecimal())
print(num.isnumeric())
结果:
False
False
True
支持的字符:
isdigit:支持 unioncode,全角,byte,汉字
isdecimal:支持 unioncode,全角,
isnumeric:支持 unioncode,全角,汉字
报错:
isdigit不会报错,后两种在byte判断时会报错
15、判断字符串是否为有效标识符(可做为函数名称)
#S.isidentifier() -> bool
t_code = 'test'
print(t_code.isidentifier())
结果:返回True
t_code = '23test'
print(t_code.isidentifier())
结果:返回False
16、判断字符串是否全小写
#S.islower() -> bool
t_code = 'kongzhagen'
print(t_code.islower())
结果:返回True
t_code = 'kongzHagen'
print(t_code.islower())
结果:返回False
17、判断字符串是否全整型数字
#S.isnumeric() -> bool
t_code = ''
print(t_code.isnumeric())
结果:返回True
t_code = '123d'
print(t_code.isnumeric())
结果:返回False
t_code = '123.123'
print(t_code.isnumeric())
结果:返回False
18、判断所有字符是否可打印
#S.isprintable() -> bool
t_code = '123KKK'
print(t_code.isprintable())
返回:True
t_code = ''
print(t_code.isprintable())
返回:True
t_code = 'KKK\n\t'
print(t_code.isprintable())
返回:False
19、判断字符中是否全为空格
#S.isspace() -> bool
t_code = ' '
print(t_code.isspace())
结果:返回True
t_code = '123 KKK'
print(t_code.isspace())
结果:返回False
20、判断字符串是否为标题格式(首字母大写)
#S.istitle() -> bool
t_code = 'Today Is A Good Day'
print(t_code.istitle())
结果:True
t_code = 'Today Is A Good day'
print(t_code.istitle())
结果:False
t_code = 'TODAY IS'
print(t_code.istitle())
结果:False
21、判断字符串是否全大写
#S.isupper() -> bool
t_code = 'Today Is A Good day'
print(t_code.isupper())
结果:False
t_code = 'TODAY IS'
print(t_code.isupper())
结果:True
22、字符串连接
#S.join(iterable) -> str
t_code = 'Today Is A Good Day'
t1_code = '.'.join(t_code)
print(t1_code)
结果:T.o.d.a.y. .I.s. .A. .G.o.o.d. .D.a.y
23、左对齐,达不到指定长度,右则填充
#S.ljust(width[, fillchar]) -> str
t_code = 'Today Is A Good Day'
print(t_code.ljust(,'*'))
结果:Today Is A Good Day***
24、转小写
#S.lower() -> str
t_code = 'Today Is A Good Day'
print(t_code.lower())
结果:today is a good day
25、左边去除指定字符,默认为空格
# S.lstrip([chars]) -> str
t_code = 'Today Is A Good Day'
print(t_code.lstrip('T'))
结果:oday Is A Good Day
t_code = ' Today Is A Good Day'
print(t_code.lstrip())
结果:Today Is A Good Day
26、
maketrans
27、partition
按指定的字符拆分字符串,分头、分隔串、尾,未找到指定的分隔符,头返回自己,后面两个返回空
#S.partition(sep) -> (head, sep, tail)
t_code = 'TodayIs A Good Day'
print(t_code.partition('a'))
结果:('Tod', 'a', 'yIs A Good Day')
print(t_code.partition('P'))
结果:('TodayIs A Good Day', '', '')
28、replace:字符串替换
将老字符串替换为新字符串,可指定替换次数
#S.replace(old, new[, count]) -> str
t_code = 'TodayIs A Good Day,To today'
print(t_code.replace('T','M',))
结果:ModayIs A Good Day,Mo today
29、rfind:返回查询到的字符串的最大索引
#S.rfind(sub[, start[, end]]) -> int
t_code = 'TodayIs A Good Day,To today'
print(t_code.rfind('d'))
结果:
30、rindex:类似rfind,但如果没找到会报错
#S.rindex(sub[, start[, end]]) -> int
t_code = 'TodayIs A Good Day,To today'
print(t_code.rindex('p'))
结果:
Traceback (most recent call last):
File "C:/51py/day1/study.py", line 90, in <module>
print(t_code.rindex('p'))
ValueError: substring not found
31、rjust:右对齐,左侧填充字符
#S.rjust(width[, fillchar]) -> str
t_code = 'Today'
print(t_code.rjust(,'*'))
结果:*****Today
32、rpartition:类似partition,如果未找到字符串,则空值在左边
#S.rpartition(sep) -> (head, sep, tail)
t_code = 'Today is a good day'
print(t_code.rpartition('isa'))
结果:('', '', 'Today is a good day')
33、rsplit:分割字符串,从右边开始
#S.rsplit(sep=None, maxsplit=-) -> list of strings
t_code = 'Today is a good day'
print(t_code.rsplit('o',))
结果:['Today is a go', 'd day']
34、rstrip:右边去空格
#S.rstrip([chars]) -> str
t_code = ' Today is a good day '
print(t_code.rstrip())
结果: Today is a good day
35、splitlines:方法返回一个字符串的所有行列表,可选包括换行符的列表(如果num提供,则为true)
#S.splitlines([keepends]) -> list of strings
t_code = 'Today\n is\n a\n good\n day'
print(t_code.splitlines())
print(t_code.splitlines())
print(t_code.splitlines())
结果:
['Today', ' is', ' a', ' good', ' day']
['Today', ' is', ' a', ' good', ' day']
['Today\n', ' is\n', ' a\n', ' good\n', ' day']
36、startswith:如果字符串以指定的字符为前缀,则返回true,否则返回false
#S.startswith(prefix[, start[, end]]) -> bool
t_code = 'Today\n is\n a\n good\n day'
print(t_code.startswith('Today'))
结果:True
37、strip:去除字符串前后的空格
#S.strip([chars]) -> str
t_code = ' Today\n is\n a\n good\n day '
print(t_code.strip())
结果:
Today
is
a
good
day
38、swapcase:大小写互转
#S.swapcase() -> str
t_code = ' Today Is a Good Day '
print(t_code.swapcase())
结果: tODAY iS A gOOD dAY
39、title:返回的字符串为title格式,首字母大写
#S.title() -> str
t_code = ' today is a Good Day '
print(t_code.title())
结果:Today Is A Good Day
40、maketrans:用于创建字符映射的转换表,两个参数为长度相等的字符串
#B.maketrans(frm, to) -> translation table
intab = "aeiou"
outab = "1234k"
trantab = t_code.maketrans(intab,outab)
print(trantab)
结果:{: , : , : , : , : }
41、translate:根据参数table给出的表转换字符中的字符
# S.translate(table) -> str
t_code = ' today is a Good Day '
trantab = {:}
print(t_code.translate(trantab))
结果: tod1y is Good D1y
42、ord与chr是配对函数
>>> chr()
'A'
>>> ord('A')
43、upper:将字符串转为大写
#S.upper() -> str
t_code = ' today is a Good Day '
print(t_code.upper())
结果:TODAY IS A GOOD DAY
44、zfill:数字填零
#S.zfill(width) -> str
t_code = ''
print(t_code.zfill())
结果:
45、汇总
str = 'https://www.baidu. com234'
# print(str.capitalize()) # 第一个字母大写
# print(str.count('w')) # 字符在字符串中出现的次数
# print(str.endswith('com')) # 字符串是否以com结尾
# print(str.expandtabs(tabsize=)) # 字符串中的tab转为两个空格
# print(str.find('bai')) # 返回字符串中bai的索引
# print(str.rfind('bai')) # 返回字符串中bai的索引,从右边找
# print(str.index('bai')) # 返回字符串中bai的索引,未找到会报错
# print(str.rindex()) # 返回字符串中bai的索引,未找到会报错(从右边找)
# print(str.isalnum()) # 如果所有字符都是数字或字母,则返回True
# print(str.isalpha()) # 如果所有字符都是字母,则返回True
# print(str.isnumeric()) # 如果所有字符都是数字,则返回T
# print(str.isdecimal()) # 可解释为十进制数,则返回True
# print(str.isdigit()) # 可解释为数字,则返回True
# print(str.islower()) # 字符串中的字母都小写,则返回True(可以有其它字符)
# print(str.isupper()) # 字符串中的字母都大写,则返回True(可以有其它字符)
# print(str.isspace()) # 字符串中全是空格,则返回True
# print(str.istitle()) # 如果字符串是标题化的,则返回True(每个单词首字母大写,其它小写)
# print(str.ljust()) # 字符串左对齐,长度100
# print(str.rjust()) # 字符串右对齐,长度100
# print(str.lower()) # 所有字符转小写
# print(str.lstrip()) # 去掉字符串左边的空格
print str.replace('t','',) # 将p 替换为2,替换2次
print str.rfind('o') # 从右边查找第一个o所在的位置
print str.rindex('o') # 从右边查找第一个o所在的位置的索引
print str.partition('du') # 从左边找到第一个du,并以之分隔字符串,返回列表
print str.rstrip() # 去掉右边的空格
print str.split('w',) # 以w为分隔符,切分字符串
print str.splitlines() # 以行做为分隔符
print str.startswith('http') # 是否以http开头
print str.swapcase() # 翻转大小写
print str.title() # 将string标题化,所有单词首字母大写,其它小写
print str.upper() # 所有字母大写
print str.zfill() # 返回150个字符,原字符串右对齐,前面填充0
python数据类型之str用法的更多相关文章
- Python学习笔记之基础篇(三)python 数据类型 int str bool 详谈
python 的数据类型: 1.int:存放 1,2,3 等数据 ,用于数字的运算 2.bool :True, False 用于判断 3.str:字符串,用来存储少量的数据 4.list : 数组的 ...
- python数据类型之int用法
1.查看整型的用法 CODE:print(dir(int))['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', ...
- Python——数据类型之str
本篇主要内容: 1.str元素的访问 2.str内置43个方法使用示例 str就是储存各种东西的字符串. 他的方法也是最多的...有各种各样的神奇魔法. 1.str的访问,str可以想列表那样访问每一 ...
- Python 数据类型及其用法
本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点型以及布尔类型.这些基本数据类型组 ...
- day01-day04总结- Python 数据类型及其用法
Python 数据类型及其用法: 本文总结一下Python中用到的各种数据类型,以及如何使用可以使得我们的代码变得简洁. 基本结构 我们首先要看的是几乎任何语言都具有的数据类型,包括字符串.整型.浮点 ...
- Python数据类型的内置函数之str(字符串)
Python数据类型内置函数 - str(字符串) - list(列表) - tuple(元组) - dict(字典) - set(收集) str(字符串)的一些操作 - 字符串相连方法 # 字符串的 ...
- python基础-2 编码转换 pycharm 配置 运算符 基本数据类型int str list tupple dict for循环 enumerate序列方法 range和xrange
1.编码转换 unicode 可以编译成 UTF-U GBK 即 #!/usr/bin/env python # -*- coding:utf-8 -*- a = '测试字符' #默认是utf-8 a ...
- python中的str.strip()的用法
python中字符串str的strip()方法 str.strip()就是把字符串(str)的头和尾的空格,以及位于头尾的\n \t之类给删掉. 例1:str=" ABC"prin ...
- Python学习笔记(五)--Python数据类型-数字及字符串
Python数据类型:123和'123'一样吗?>>> 123=='123'False>>> type(123)<type 'int'>>> ...
随机推荐
- SQL调用系统存储过程整理
SQL系统存储过程用法整理: xp_cmdshell --*执行DOS各种命令,结果以文本行返回. xp_fixeddrives --*查询各磁盘/分区可用空间 xp_loginconfig --*报 ...
- shell脚本 gawk语言 综采话单 对账 字段核对
今天被分配到对账组下的字段程序的了解和修改,在 SecureCRT 下的 run.sh 是字段对账的主程序,其中run.sh文件中含有gawk的代码. 程序的主要功能为 有两个文件夹 source存的 ...
- Day07_面向对象第二天
1.构造方法(掌握) 1.构造方法的特点(掌握) A.方法名必须和类名保持一致 B.没有返回值类型并且没有具体的返回值 2.构造方法的作用(掌握) 给对象的属性初始 ...
- Linux TC (traffic control)
在着手学习TC采用如下单位来描述带宽: mbps = 1024 kbps = 1024 * 1024 bps => byte/s mbit = 1024 kbit => kilo bit/ ...
- 世纪互联运营的Microsoft Azure正式支持FreeBSD虚拟机镜像
自2012年开始,微软云计算与企业事业部和Citrix思杰,NetApp达成合作,共同开发出第一版针对Hyper-V虚拟设备驱动以及相关的用户态程序,并将此称之为集成服务(Integration Se ...
- Oracle执行语句跟踪(1)——使用sql trace实现语句追踪
系统上的某个接口提交数据经常超时(超过3秒),而我单独在后台数据库(Oracle)执行insert,只需要17ms.提交数据的客户端没有任何的调试日志,只能通过跟踪后台语句记录实际调用过程中的数据库执 ...
- tyvj 1055 区间dp
P1055 沙子合并 时间: 1000ms / 空间: 131072KiB / Java类名: Main 描述 设有N堆沙子排成一排,其编号为1,2,3,…,N(N<=300).每堆沙子 ...
- CSS控制a标签链接的四种状态
/*CSS链接的四种状态 *a:link 普通的.未被访问的链接样式 *a:visited 用户已访问的链接样式 *a:hover 鼠标指针位于链接上方样式 *a:active 链接被点击的时刻样式 ...
- hdu 1548 (dijkstra解法)(一次AC就是爽)
恭喜福州大学杨楠获得[BestCoder Round #4]冠军(iPad Mini一部) <BestCoder用户手册>下载 A strange lift Time Limit: 200 ...
- Jquery图片上传预览效果
uploadPreview.js jQuery.fn.extend({ uploadPreview: function (opts) { var _self = this, _this = $(thi ...