字符串

阅读目录                      

str与int、bool之间的转换

str的切片

str的索引

str的基本操作

两种格式化输出方式

字符串和列表之间的转换

 

str与int、bool之间的转换           

# str --> int
a = '1'
print(int(a)) #1

# str --> bool
a = '1'
print(bool(a)) #True
Viwe Code

 

str的切片                       

#字符串切片顾头不顾尾,第一个元素序号为0
a = 'abcde'

# 复制字符串
print(a[:]) #abcd

print(a[1:4]) #bcd

#步长为2
print(a[0:4:2]) #ac

#步长-1倒序
print(a[4:1:-1]) #edc
View Code

 

str的索引                  

a = 'abcde'

#切片索引,首位序号为0
print(a[1]) #b

#index 通过元素索引序列号(其他数据类型皆可用)
print(a.index('a')) #0

#find 通过元素索引序列号(只有字符串可用)
print(a.find('a')) #0
View Code

 

str的基本操作                                                        

a = 'abcde'

#startswith 确认首字母‘a’开头
print(a.startswith(a)) #True

#endswith确认尾字母‘e’开头
print(a.endswith('e')) #True

#capitalize() 首字母大写
print(a.capitalize()) #Abcde

#title() 首字母大写(有空格)
print(a.title()) #Abcde

#upper() 全部大写
print(a.upper()) #ABCDE

#lower() 全部小写
print(a.lower()) #abcde

#swapcase() 大小写翻转
print(a.swapcase()) #ABCDE

#count() ‘a’有几个
print(a.count('a')) #1

#replace() 替换元素(只有字符串可用)
print(a.replace('a','1')) #1bcde

#strip() 去空格或者其他元素
print(a.strip('a')) #bcde
View Code

 

两种格式化输出方式             

#format()
name = 'sx'
age = 28
print('我的名字{},我的年龄{}'.format(name,age)) #我的名字sx,我的年龄28
print('我的名字{0},我的年龄{1}'.format(name,age)) #我的名字sx,我的年龄28
print('我的名字{a},我的年龄{b}'.format(a = name,b = age)) #我的名字sx,我的年龄28

#%s字符串  %d数字
name = 'sx'
age = 22
print('我的名字%s,我的年龄%s'%(name,age)) #我的名字sx,我的年龄22
View Code

 

字符串和列表之间的转换                                      

#str --> list split()
a = 'abcde'
#以元素‘c’作为切割点
print(a.split('c')) #['ab', 'de']

#list --> str join()
lis = ['a','b','c','d']
#列表内为数字不可转变
print('|'.join(lis))
View Code
posted @ 2019-08-29 17:15  supreme_me  阅读(200)  评论(0)    收藏  举报