Python程序设计--第4章 字符串与正则表达式

只学习了字符串,正则太复杂了,没看。

x='''He said "Let's go"'''  #字符串可用单引号、双引号、三单引号、三双引号作为界定符,而且可以相互嵌套
name='tom'
age=20
s='{0} is {1} years old'.format(name,age)   #使用format()格式化,tom is 20 years old
s="the number {0} in Hex is {0:#x},in binary is {0:#b}".format(age)   #'the number 20 in Hex is 0x14,in binary is 0b10100'

# 字符串检索  find,index,count,in
x='abc123 ss'
i=x.find('123')  #3,找到了
i=x.find('456')  #-1,没找到
i=x.index('123')  #3,找到了,与find一致
#i=x.index('456')  #没找到,触发异常substring not found
i=x.count('123')  #1,出现的次数
i=x.count('456')  #0
i="123" in x  #True
i="qq" in x   #False
i="qq" not in x  #True

#字符串分割
x='2019-12-31'
x=x.split('-')   #指定分割字符,['2019', '12', '31']
x='let us go	 home'
x=x.split()   #缺省分隔符为空字符,或
,	等

#字符串连接
x=['2019', '12', '31']
sep='-'    #分隔符,允许为空
x=sep.join(x)   #2019-12-31
x=''.join(['123','abc'])   #123abc

#大小写
x='What is your name?'
x=x.lower()    #全部小写
x=x.upper()    #全部大写
x=x.capitalize()   #一个首字母大写
x=x.title()        #全部首字母大写

#计算表达式的值
x='3*2-1'
y=eval(x)
x=2
y=3
v=eval('x**2+2*y-3')  #表达式计算

#检索
x='abc123'
y=x[3:]  #123
y=x[-1]  #3

#删除端部空格,或指定字符
#strip,rstrip,lstrip
x='   abc   '
x=x.strip()    #abc
x='@abc'
x=x.strip('@')  #abc

#对齐,填充及对齐
#center,ljust,rjust,返回指定宽带的新字符串,实现居中、左对齐、右对齐
#可设置字符宽度和填充字符串,缺省为空格
x='a'
y='abc'
x1=x.center(2)
y1=y.center(20,'-')
x1=x.rjust(20,'-')
x1="".center(20,'a')   #实现单字符的n次重复

#替换
s='abc123'
s1=s.replace('b','pp')  #appc123
原文地址:https://www.cnblogs.com/imhuanxi/p/11187172.html