Python基本数据类型(二)

链接:

Python基本数据类型(一)

本章学习

  1. 熟悉字符串str的部分常用方法 

其中的join很重要,一定要记住熟悉。

#!/usr/bin/env python
#-*- coding:utf8 -*-

#判断字符串中是否存在不可见字符 如:\t \n等
test = "ddhjj\tsjsh"
print(test.isprintable()) #返回False

#判断字符串是否全部是空格  包含的话是返回False 
#与""不一样,""这个是空字符串,不包含空格
test = "  " 
print(test.isspace()) #返回True


# istitle() 判断是否是标题
test = "I am a jeek"
print(test.istitle()) #返回False 
v1 = test.title() #转换为标题
print(v1) #打印 I Am A Jeek
print(v1.istitle()) #返回True

#join方法很重要!!!!
#将字符串中的每一个元素按照指定分隔符进行拼接
test = "我是一个极客"
v1 = "_".join(test)
print(v1) #打印出 我_是_一_个_极_客

#使得字符串在宽度为20下,居中显示,第一个参数是宽度,第二个数字是填充的字符,只能是一个字符
test = "abcabc"
print(test.center(20))#       abcabc
print(test.center(20,"*"))#*******abcabc*******
#将字符串放在最左边,向右填充*
print(test.ljust(20,"*"))#abcabc**************
#将字符串放在最右边,向左填充*
print(test.rjust(20,"*"))#**************abcabc

#转换为大/小写
test = "Abc"
print(test.upper())
print(test.lower())
#判断是否全部是大/小写
print(test.isupper())
print(test.islower())

#以下三个方法也可以去掉特殊字符,如\t \n
test = " pAbc "
print(test.lstrip())#去掉左边的空白
print(test.rstrip())#去掉右边的空白
print(test.strip())#去掉看两边的空白

#优先最多匹配
test = "pAbcp"
print(test.lstrip("p"))#去掉左边的p字符串
print(test.rstrip("p"))#去掉左边的p字符串
print(test.strip("p"))#去掉左边的p字符串


#转换对应关系的字符串
v = "askojfiuiiojsnaniwe"
m = str.maketrans("aeiou","12345")#形成一个对应关系 1->a 2->e 
new_v = v.translate(m)#将对应关系转换过来后的字符串
print(new_v)

#分隔字符串
test = "test" 
#partition() 和rpartition()只能分隔后分三组 并且需要分隔的字符是包含在里面的
print(test.partition("s"))  #('te', 's', 't')
print(test.rpartition("s")) #('te', 's', 't') 从右边开始分隔
#split()和rsplit()分隔后可分为多组,但是需要分隔的字符串不包含在里面
print(test.split("s"))#['te', 't']
print(test.rsplit("s"))# ['te', 't'] 从右边开始分隔
test = "testtesttest"
print(test.split("e",2))#['t', 'stt', 'sttest'] 只执行对e的两次分隔。	
#分隔,只能根据换行进行分隔,True,False是否保留换行符
#True 保留,False 不保留
test = "asdf\nssf\nss\nfff"
print(test.splitlines(False))#['asdf', 'ssf', 'ss', 'fff']
print(test.splitlines(True))#['asdf\n', 'ssf\n', 'ss\n', 'fff']

#大小写互转 大写转为小写 小写转为大写
test = "yJc"
print(test.swapcase()) #YjC

#替换字符串
test = "YjcYjcYjc"
v1 = test.replace("Y","y")#将Y替换为y  yjcyjcyjc
v2 = test.replace("Y","y",2) #只替换前2个Y yjcyjcYjc
print(v1,v2)

=========================================================================================

平常我们使用的关于字符串的方法大致重要的,频率大的有:join,split,replace,upper,lower,find,strip,那么除了这些还有哪些需要我们注意的呢?还有索引,切片,长度,列表知识,以下是这些的代码。

 

#索引
test = "Abc"
print(test[1]) #打印出b
#切片
#起始包含[ }结束不包含
print(test[0:1]) #打印出A 0:1的意思是下表为0-1的但是关系是[ }
print(test[0:-1]) #打印出Ab 

#长度len() Python3是返回的是当前字符串由几个字符串组成
print(len(test)) #返回3

#列表
v = [11,22,33,"aaa"]
print(len(v))#对列表进行统计长度 返回为4

#要想逐个打印出test里面的字符,可以使用for循环
for s in test:
	print(s)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值