数据类型转换
#int----->str s = 1 i = str(s) print(i) #str----->int s = '123' i = int(s) print(i) #int------->bool i = 3 b = bool(i) print(b)
# s = '' ------>Fasle
#非空字符串都是True
#s = "0" --------->True
字符串的索引与切片
切片:顾头不顾尾
s = 'ABCDLSESRF'
s1 = s[0]
print(s1)
s2 = s[2]
print(s2)
s3 = s[0:3] #顾头不顾定
print(s3)
s4 = s[-1]
print(s4)
s5 = s[0:]
print(s5)
s6 = s[:]
print(s6)
s7 = s[0:5:2]
print(s7)
s8 = s[3::-1]
print(s8)
s9 = s[3::-2]
print(s9)
s10 = s[-1::-1]
print(s10)
s10 = s[::-1]
print(s10)
A
C
ABC
F
ABCDLSESRF
ABCDLSESRF
ACL
DCBA
DB
FRSESLDCBA
FRSESLDCBA
字符串操作
s = 'alexusir' s1 = s.capitalize() #首字母大写 print(s1)
Alexusir
s2 = s.upper() #全部字母大写 print(s2)
############ ALEXUSIR
s3 = s.lower() #全部字母小写 print(s3)
alexusir
s4 = s.swapcase() #字母大小写翻转 print(s4)
aLEXUSIR
每个隔开(特殊字符或者数字)的单词的字母大写
s = 'alex open user' s5 = s.title() print(s5) ########### Alex Open User
居中和填充
s = 'alexUser' s6 = s.center(20,'#') #居中和填充 print(s6) ######alexUser######
table 键位
s = 'all\tuser' s7 = s.expandtabs() #table键 print(s7) all user
字符长度
s = '123dfjlasjflasjfklasjf地方' s8 = len(s) print(s8) 24
判断字符串中以什么开头和结尾
s = 'alexWUsir' s9 = s.startswith('alex') print(s9) True
s = 'alexWUsir' s9 = s.startswith('alex') print(s9) s10 = s.startswith('U',5) print(s10) True True
前缩进后缩进
s = ' string ' s12 = s.strip() print(s12) string
username = input('请输入姓名: ').strip() if username == "tim": print('gogogogo')
计数
s = 'alexaa wusiral' s10 = s.count('al') print(s10) 2
split
s = 'cis h3 c' s11 = s.split() print(s11) s = 'cis:h3:c' s12 = s.split(':') print(s12) ['cis', 'h3', 'c'] ['cis', 'h3', 'c']
format的三种玩法,格式化输出
s = '我叫{},今年{},爱好{},再说一下我叫{}'.format('tim',22,'girl','tim') print(s) s = '我叫{0},今年{1},爱好{2},再说一下我叫{0}'.format('tim',22,'girl','tim') print(s) s = '我叫{name},今年{age},爱好{hobby},再说一下我叫{name}'.format(name='tim',hobby='girl',age=33) print(s) 我叫tim,今年22,爱好girl,再说一下我叫tim 我叫tim,今年22,爱好girl,再说一下我叫tim 我叫tim,今年33,爱好girl,再说一下我叫tim
字符串替换
s = 'skdfjlasdfjlasdfjlsdfjls' s13 = s.replace('jl','xxxxxxxxxxxxxxx') print(s13) s14 = s.replace('jl','xxxxxxxxxxxxxxx',1) print(s14) skdfxxxxxxxxxxxxxxxasdfxxxxxxxxxxxxxxxasdfxxxxxxxxxxxxxxxsdfxxxxxxxxxxxxxxxs skdfxxxxxxxxxxxxxxxasdfjlasdfjlsdfjls