5月25号,Python的字符串和运算符

在这里插入图片描述

1 字符串

1.1 格式化字符串

输入:

print(6+6,'6'+'6','Sher'+'o')

可以得到:

12 66 Shero

其中,后两个输出结果就是一种字符串的拼接

1.1.1 拼串

下面我们举个栗子:

s='Hello'
print('s = '+s)

输出:

s = Hello

此即典型的拼串,能使得程序的体验感更好,但用得不多。

1.1.2 参数传递(传参)

把上个例子改一下:

s='Hello'
print('s = ',s)

输出的结果和原来一样,这就是传参

1.1.3 占位符

%d:整数占位
%s:字符占位
%f:小数占位

%s为例,输入:

print('i love %s'%'study')

输出:

i love study

但这种方式每换一次占位对象,就要重写一遍,很不方便,于是:

a='i love %s'
print(a%'Shero')
print(a%'study')

也能得到:

i love Shero
i love study

又例如,输入:

s='s = %s'%'Hello'
print(s)

同样得到:

s = Hello

但若输入:

s='s1 = %s,s2 = %s'%'Hello'
print(s)

系统将给出:

TypeError: not enough arguments for format string

原因就是:只给了一个Hello,系统不知道该给谁占位。

改成:

s='s1 = %s,s2 = %s'%('Hello','World')

则可通过并输出:

s1 = Hello,s2 = World

1.1.4 格式化的方式

  • f{ }

输入:

s1='钢铁侠'
s2='葫芦娃'
a=f'Hello {s1},{s2}'
print(a)

得到:

Hello 钢铁侠,葫芦娃

这里,{ }中的s1,s2均为变量,f{ }表示在字符擦混中添加变量,可以一个或多个。

另一个栗子:

a=f'诗词{s}'
print(a)

结果报错,因为s没有指向:

NameError: name 's' is not defined

我们增加一行后:

s='歌赋'
a=f'诗词{s}'
print(a)

输出:

诗词歌赋
  • str.format()

这里的format是一个方法(形如y.XXX()的是方法,而函数形如XXX()),也是特殊的函数。它从Python2.6开始适用。当我们输入:

s='I like {a}'
a=s.format('python')

系统会报错:

KeyError: 'a'

原因是没找到关键词a,我们可以改一下:

s='I like {}'
a=s.format('python')
print(a)

得到:

I like python

或者改成:

s='I like {0}'
a=s.format('python')
print(a)

结果不变,但当变成除不加或0之外的,如1、2:

s='I like {1}'
a=s.format('python')
print(a)

结果就成了:

IndexError: tuple index out of range

原因是:{ }的下标从0开始,要么不写,要么0

另一个栗子,当我们输入:

s='I like {}, {}'
a=s.format('Python','Java')
print(a)

可以运行,得到结果:

I like Python, Java

此时,我们把{ }中添加下标:

s1='I like {0}, {1}'
s2='I like {1}, {0}'
a=s1.format('Python','Java')
b=s2.format('Python','Java')
print(a)
print(b)

得到结果:

I like Python, Java
I like Java, Python

可以知道,下标的大小说明了占位的顺序。而若用 {1},{2} 作为下标:

s1='I like {1}, {2}'
a=s1.format('Python','Java')
print(a)

运行出错:

IndexError: tuple index out of range

下面再给出一个栗子,同时用到了整数占位%d和字符占位%f

d='Zhangsan is %d years old, %s is older.'%(22,'Lisi')
print(d)

得到:

Zhangsan is 22 years old, Lisi is older.

第二种方式是:

e='Zhangsan is {0} years old, {1} is older.'
print(e.format(22,'Lisi'))

第三种方式是:

a=22
b='Lisi'
w=f'Zhangsan is {a} years old, {b} is older.'
print(w)

得到的结果都和第一种是一样的。

因此,我们总结如下:

当有变量指引时,使用f{ };当没有变量指引时,需要往{}里传递,使用str.format()

1.2 字符串的其它操作

1.2.1 字符串的长度

我们使用len()函数来获取字符串的长度:

a='Python'
print(len(a))
print(len('ILOVEYOU'))

得到:

6
8

1.2.2 字符串的最大、最小值

我们使用max()min()函数来得到字符串的最大、最小值。

a='1234567'
b='Shero love Python'
print(max(a),min(a),min(b),max(b))

得到:

7 1   y

注意这里,min(b)的结果是‘ ’,返回的是空格。这是因为,空格的ASCII码值是比所有字母都小,用ord()函数可以证实:

print(ord(' '),ord('y'),ord('7'),ord('1'))

得到:

32 121 55 49

1.2.3 字符串的分割

我们使用split()函数分割字符串,split()返回的是一个列表。在Python中,它常用于爬虫,例如:当我们找到src='XXXXXXXXXXX.jpg',为了便于操作,我们可能仅取后三位'XXX.jpg',这时就需要我们以 . 分割。

a='I love China'
b='www.baidu.com'
print(a.split(' '))
print(b.split('.'))

得到:

['I', 'love', 'China']
['www', 'baidu', 'com']

注意:在分割字符串时我们要观察以哪个为分割对象最为方便。

1.2.4 字符串的拼接

我们用join()函数进行拼接,形如' '.join(XX),引号中的内容为拼接方式,括号中的内容为拼接对象:

a='IloveChina'
b='www.baidu.com'
print('-'.join(a))
print(' '.join(b))

第一个以-拼接,第二个以空格拼接,运行的拼接结果为:

I-l-o-v-e-C-h-i-n-a
w w w . b a i d u . c o m

1.2.5 字符串的去空格

首先,为什么需要去空格?
答:有的数据,例如XXXXXXXXXX.jpg\r\n,后面的若\n不去掉,会增加后续操作的难度。
s.strip():左右两边都要去空格
s.lstrip():左边去空格
s.rstrip():右边去空格

a=' I love China '
print(a.strip())
print(a.lstrip())
print(a.rstrip())

输出结果为:

I love China
I love China 
 I love China

1.2.6 字符串的大小写

s.upper():全部大写
s.lower():全部小写
s.isupper():判断是不是全部大写,返回bool型
s.islower():判断是不是全部小写,返回bool型

输入:

a='I love China'
b='i love china'
print(a.upper())
print(a.lower())
print(a.isupper())
print(b.islower())

运行得到:

I LOVE CHINA
i love china
False
True

2 运算符

2.1 运算符的概念

  • 用于执行程序代码运算,针对一个以上操作数项目来运算
    例如:2+3中,23是操作数,+是运算符。

2.2 运算符的分类

2.2.1 算术运算符

  • 加号+

输入:

x=1+2
print('x =',x)

运行结果:

x = 3

又输入:

x='Hello'+' '+'world'
print('x =',x)

结果得到:

x = Hello world
  • 减号-
    输入:
x='Python'-'y'
print('x =',x)

得到:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

因此我们可知:两个字符串不能相减。再输入:

x=5-True
print('x =',x)

得到:

x = 4
  • 乘号*

输入:

x=5*2
print('x =',x)

得到:

x = 10

又输入:

x='a'*2
print('x =',x)

得到:

x = aa

也就是说,字符串与整数相乘的含义是:将字符串重复指定次数

再输入:

x='a'*'b'
print('x =',x)

得到运行错误:

TypeError: can't multiply sequence by non-int of type 'str'

可知,两个字符串不能相乘,自然也不能相除,结合之前不能相减,我们得到,字符串之间只能做加法

  • 除号/

输入:

x=6/2.0
print('x =',x)

得到:

x = 3.0

可知,只要有浮点数参与算术运算,返回的都是浮点数。又输入:

x=6/0
print('x = ',x)

得到:

ZeroDivisionError: division by zero

这里是因为除数不能为0。再输入:

x=7/3
print('x = ',x)

得到:

x =  2.3333333333333335
  • 取整//

接着上一个例子:

x=7//3
print('x = ',x)

此时,运算结果为上一结果的整数部分:

x =  2
  • 取余%

进一步输入:

x=7%3
print('x = ',x)

得到余数:

x =  1
  • 幂运算**

我们输入:

x=7**3
print('x = ',x)

得到:

x =  343

幂运算也可用来开方:

x=16**0.5
print('x = ',x)

结果为:

x =  4.0

2.2.2 赋值运算符

x=2
x+=3
print('x=',x)
x-=3
print('x=',x)
x*=3
print('x=',x)
x/=3
print('x=',x)
x//=3
print('x=',x)
x%=3
print('x=',x)

得到:

x= 5
x= 2
x= 6
x= 2.0
x= 0.0
x= 0.0

其中,x+=3等价于x=x+3,其它运算同理,但在编程中我们一般写成上述形式。

2.2.3 比较运算符

  • 返回的是bool类型
  • 常见的比较运算符:> >= < <= == !=

例如输入:

result=10>20
print('result=',result)

得到:

result= False

又比较字符:

result='2'>'1'
print('result=',result)

得到:

result= True

我们尝试比较字符串:

result='2'>'11'
print('result=',result)

结果还是:

result= True

这是为什么呢?原因在于:

若出现多个字符,比较的方式是对位比较。前一位已经比出大小,则返回结果;否则,比下一位。

再有如下:

result='a'>'b'
print('result=',result)
result='ab'>'b'
print('result=',result)

得到:

result= False
result= False

我们可以用ord()函数来检验一下:

print(ord('a'),ord('b'),ord('c'),ord('1'),ord('2'))

得到:

97 98 99 49 50

又输入:

result=3==3
print('result=',result)
result='Hello'=='Hello'
print('result=',result)
result='abc'=='bcd'
print('result=',result)
result='abc'!='bcd'
print('result=',result)
result=1==True
print('result=',result)

得到:

result= True
result= True
result= False
result= True
result= True

引入isis not 比较,我们再来看:

result=0==False
print('result=',result)
result=0 is False
print('result=',result)
result=0 is not False
print('result=',result)

输出结果为:

result= True
result= False
result= True

因此,我们可知:

is是用来比较两个对象是否是同一个对象,比的是id()值;
is not是用来比较两个对象是否不是同一个对象,比的是id()值;
==比较的是两个对象的值是否相等,比的是value()值;
!=比较的是两个对象的值是否不等,比的是value()值。

可稍作验证:

a=1
b=1
print(a is b)
print(id(a),id(b))

得到相同的id值:
True
1678934128 1678934128

2.2.4 逻辑运算符

  • not:逻辑非,可对符号右侧值进行非运算,其中的非bool值会转换为bool值运算

例如:

a=1
a=not a
print(a)

得到:

False

又如:

a=None
a=not a
print(a)

得到:

True

或者:

a=[]
a=not a
print(a)

同样得到:

True

因此:

0,空串''None[],还有一个表示空性的值会转化为False,剩下的全是True

  • and:逻辑与,可对符号两侧进行与运算,找False
result=True and True
print('result=',result)
result=True and False
print('result=',result)
result=False and True
print('result=',result)
result=False and False
print('result=',result)

结果为:

result= True
result= False
result= False
result= False

因此,与运算的规律可总结为:

FalseFalse,或者说,只有两侧都为True,才会返回True。
通俗点说,第一个值为False,第二个值爱啥啥我不看。

我们可以类比“爱情”,房、车、存款……只要一个不满足,一个是F,就不嫁给你了,结果就是F。只有当两个人互相爱着对方,才能称之为“爱情”。

在这里插入图片描述

  • or:逻辑或,找True
result=True or True
print('result=',result)
result=True or False
print('result=',result)
result=False or True
print('result=',result)
result=False or False
print('result=',result)

得到:

result= True
result= True
result= True
result= False

因此,不难看出或运算规律:

TrueTrue,或者说,只有两侧都为False,才会返回False。
通俗点说,第一个值为True,第二个值爱啥啥我不看。

我们可以类比“亲情”,我们与父母,任何一方烦另一方,我们还是亲人,只有当彼此互不相认,才能称之为“不是亲情”。
在这里插入图片描述

2.2.5 非bool值的与、或运算

  • Python会先将其当做bool值运算,最终返回原值。
  • 与运算:若第一个值是False,则返回第一个值;否则返回第二个值。

验证上述结论,输入:

result=1 and 2
print('result=',result)
result=1 and 0
print('result=',result)
result=0 and 2
print('result=',result)
result=0 and 1
print('result=',result)

得到:

result= 2
result= 0
result= 0
result= 0
  • 或运算:若第一个值是True,则返回第一个值;否则返回第二个值。

同样验证如下:

result=None or 0
print('result=',result)
result=1 or 2
print('result=',result)
result=0 or 1
print('result=',result)
result=0 or 3
print('result=',result)

得到:

result= 0
result= 1
result= 1
result= 3

这里有一个稍微特殊一点的:

result=1<2>3
print('result=',result)
result=1<2<3
print('result=',result)

结果为:

result= False
result= True

这里的1<2>31<2<3可分别看成:1< 2 and 2>31<2 and 2<3

3 两个小问题

3.1 问题一

四种格式化字符串方式实现:521 XXX 嫁给我好吗?

答:

# 方法一
girl='Shero'
print('521'+girl+', Would you marry me?')
# 方法二
a='521%s, Would you marry me?'
print(a%'Shero')
# 方法三
girl='Shero'
print(f'521{girl}, Would you marry me?')
# 方法四
s='521{}, Would you marry me?'
print(s.format('Shero'))

运行结果为:

521Shero, Would you marry me?
521Shero, Would you marry me?
521Shero, Would you marry me?
521Shero, Would you marry me?

在这里插入图片描述

3.2 问题二

现有a,b,c三变量,分别保存有三个数值,通过条件运算符获取三个值中的最大值。

print('最大值为:',a) if a>=b and a>=c else(print('最大值为:',b) if b>=a and b>=c else print('最大值为:',c))

验证如下,若赋值:

a=24
b=76
c=11
print('最大值为:',a) if a>=b and a>=c else(print('最大值为:',b) if b>=a and b>=c else print('最大值为:',c))

运行得到:

最大值为: 76

满足条件。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值