Python语言快速入门下2

目录

一、前言

二、字符串

【字符串】

【字符串格式化】

【字符串常用方法】

1)去掉空格和特殊字符

3)字符串的测试和替换函数

4)字符串的分割

5)连接字符串

6)截取字符串(切片)

7)#split()

8)lower(), upper(), capitalize(), title(), swapcase()

9)strip()、 rstrip()、Istrip()

10)值

11)关键字 in

12)startswith()、endswith()

【字符串常量】

三、异常处理

【例题1】最大公约数

【例题2】除法

【例题3】最大公约数、除法


一、前言

本文是Python语言入门的最后一节,主要讲字符串和异常处理。

二、字符串

【字符串】

字符串属于不可变序列类型,使用单引号、双引号、三单引号或三双引号作为界定符,不同界定符之间可以互相嵌套

支持序列通用方法,包括比较、计算长度、元素访问、切片等

支持一些特有的操作方法,包括格式化操作、字符串查找、字符串替换等

不支持元素增加、修改与删除等操作

Python 3.x中字符串类型为str类型

Python 3.x中,程序源文件默认为UTF-8编码

【字符串格式化】

形式:

'%[-][+][0][m][.n]格式字符'%表达式

>>> print('%10d'%3)
         3
>>> print('%.4f'%3.14159)
3.1416
>>> print('%c'%65)
A
>>> print('%s'%65)
65
>>> print('%s'%[1,2,3])
[1, 2, 3]
>>> print(str([1,2,3]))
[1, 2, 3]
>>> print('%d'%'123')
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print('%d'%'123')
TypeError: %d format: a number is required, not str
>>>

使用format()方法进行格式化

>>> print('The number {0:,} in hex is:{0:#x},the number {1} in oct is {1:#o}'.format(123456,789))
The number 123,456 in hex is:0x1e240,the number 789 in oct is 0o1425
>>> print('The number {1:,} in hex is:{1:#x},the number {0} in oct is {0:#o}'.format(123456,789))
The number 789 in hex is:0x315,the number 123456 in oct is 0o361100
>>> print('my name is {name:>20},my age is {age}.'.format(name='yjg',age=22))
my name is                  yjg,my age is 22.
>>>

【字符串常用方法】

1)去掉空格和特殊字符

3)字符串的测试和替换函数

4)字符串的分割

5)连接字符串

‘,’.join(slit)  用逗号连接 slit 变成一个字符串,slit 可以是字符,列表,字典 (可迭代的对象)。int 类型不能被连接。

6)截取字符串(切片)

>>> str='0123456789'
>>> print(str[0:3])	#截取第一位到第三位的字符
012
>>> print(str[6:])	#截取第七个字符到结尾
6789
>>> print(str[2])
2
>>> print(str[::-1])
9876543210
>>> print(str[-3:-1])
78
>>> print(str[-3:])
789
>>>
>>> s='kiwifruit,lemon,lichee,orange,peach,banana,plum,carrot,maize'
>>> print(s.find('peach'))
30
>>> print(s.find('peach',7))
30
>>> print(s.find('peach',7,20))
-1
>>> print(s.rfind('p'))
43
>>> print(s.index('p'))
30
>>> print(s.index('pea'))
30
>>> print(s.rindex('pea'))
30
>>> print(s.count('p'))
2
>>> print(s.count('pp'))
0
>>> print(s.count('ppp'))
0
>>> print(s.split(','))
['kiwifruit', 'lemon', 'lichee', 'orange', 'peach', 'banana', 'plum', 'carrot', 'maize']
>>>

7)#split()

通过指定分隔符对字符串进行切片,如果参数 num 有指定值,则分隔 num+1 个子字符串

>>> s='2022-12-26'
>>> print(list(map(int,s.split('-'))))
[2022, 12, 26]
>>> s='hello world My name is abc'
>>> print(s.split())
['hello', 'world', 'My', 'name', 'is', 'abc']
>>> print(s.split(None,4))
['hello', 'world', 'My', 'name', 'is abc']
>>> li=['kiwifruit', 'lemon', 'lichee', 'orange', 'peach']
>>> print(','.join(li))
kiwifruit,lemon,lichee,orange,peach
>>>

8)lower(), upper(), capitalize(), title(), swapcase()

>>> print('What is Your Name?'.lower())
what is your name?
>>> print('What is Your Name?'.upper())
WHAT IS YOUR NAME?
>>> print('What is Your Name?'.capitalize())
What is your name?
>>> print('What is Your Name?'.title())
What Is Your Name?
>>> print('What is Your Name?'.swapcase())
wHAT IS yOUR nAME?
>>>

9)strip()、 rstrip()、Istrip()

strip() 方法用于移除字符串头尾指定的字符 (默认为空格)

>>> print('  abc '.strip())
abc
>>> print('  abc '.rstrip())
  abc
>>> print('  abc '.lstrip())
abc 
>>> print('\nhello \nworld \n'.strip())
hello 
world
>>> print('abcdabcaba'.strip('a'))
bcdabcab
>>>

10)值

import math
print(eval('3+4'))
a,b=3,5
print(eval('a+b'))
print(eval('math.sqrt(3)'))
print(eval('b'))

7
8
1.7320508075688772
5
>>> 

11)关键字 in

print('a' in 'abcde')
print('ab' in 'abcde')
print('j' in 'abcde')

True
True
False

12)startswith()、endswith()

startswith() 方法用于检查字符串是否是以指定子字符串开头,如果是则返回True,否则返回False。如果参数 beg 和 end 指定值,则在指定范围内检查。

print('Beautiful'.startswith('Be'))
print('Beautiful'.startswith('Be',5))
print('Beautiful'.startswith('Be',0,5))
print('Beautiful'.endswith('ful'))

True
False
True
True

【字符串常量】

string.digits  所有数字

string.ascii_letters  所有字母

string.ascii_lowercase  所有小写字母

string.ascii_uppercase  所有大写字母

import string
print(string.digits)
print(string.ascii_letters)
print(string.ascii_lowercase)
print(string.ascii_uppercase)

0123456789
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
ABCDEFGHIJKLMNOPQRSTUVWXYZ

三、异常处理

  • 在编写程序的过程中,程序员通常希望识别正常执行的代码和执行异常的代码。
  • 这种异常可能是程序的错误,也可以是不希望发生的事情。
  • 为了能够处理这些异常,可以在所有可能发生这种情况的地方使用条件语句进行判断。但这么做既效率低,也不灵活,而且还无法保证条件语句覆盖了所有可能的异常。
  • 为了更好地解决这个问题,Python语言提供了非常强大的异常处理机制。通过这种异常处理机制,可以直接处理所有发生的异常,也可以选择忽略这些异常。
  • 开发人员在编写程序时,难免会遇到错误,有的是编写人员疏忽造成的语法错误,有的是程序内部隐含逻辑问题造成的数据错误,还有的是程序运行时与系统的规则冲突造成的系统错误,等等。总的来说,编写程序时遇到的错误可大致分为2类:
  • 语法错误:print “Hello,World!”  Python 3 不再支持这种写法
  • 运行错误:a=1/0
  • 在Python中,这种运行时产生错误的情况叫做异常 (Exceptions)

  • 当一个程序发生异常时,代表该程序在执行时出现了非正常的情况,无法再执行下去。默认情况下,程序是要终止的。如果要避免程序退出,可以使用捕获异常的方式获取这个异常的名称,再通过其他的逻辑代码让程序继续运行,这种根据异常做出的逻辑处理叫作异常处理。
  • 开发者可以使用异常处理全面地控制自己的程序。异常处理不仅仅能够管理正常的流程运行,还能够在程序出错时对程序进行必要的处理。大大提高了程序的健壮性和人机交互的友好性。
  • 那么,应该如何捕获和处理异常呢?可以使用try语句来实现。

正如下图所示:

【例题1】最大公约数

import math
while True:
    try:
        x,y=map(int,input('请输入两个整数:').split())
        print('%d与%d的最大公约数为: %d'%(x,y,math.gcd(x,y)))
    except ValueError:
        print('你输入的不是合法的数据,请重新输入...')

请输入两个整数:45 345
45与345的最大公约数为: 15
请输入两个整数:ssd 33
你输入的不是合法的数据,请重新输入...
请输入两个整数:-1223 345
-1223与345的最大公约数为: 1
请输入两个整数:

【例题2】除法

x=3.5
try:
    y=float(input('请输入除数:'))
    z=x/y
except ZeroDivisionError:
    print('除数不能为0')
except ValueError:
    print('除数应为数值类型')
else:
    print(x,'/',y,'=',z)

请输入除数:9
3.5 / 9.0 = 0.3888888888888889
>>> 
=====
请输入除数:0
除数不能为0
>>> 
======
请输入除数:uy
除数应为数值类型
>>>

【例题3】最大公约数、除法

x=3.5
try:
    y=float(input('请输入除数:'))
    z=x/y
except BaseException as e:
    print('你输入的不是合法的数据',e)
else:
    print(x,'/',y,'=',z)


请输入除数:8
3.5 / 8.0 = 0.4375
>>> 
======
请输入除数:gh
你输入的不是合法的数据 could not convert string to float: 'gh'
>>> 

以上,Python语言快速入门下2

祝好

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吕飞雨的头发不能秃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值