Python基础教程(二)字符串和函数

6.字符串

6.1 字符串的表示方式

6.1.1 普通字符串

普通字符串指用单引号('')或双引号(”")括起来的字符串。例如:'Hello'或"Hello"

>>> 'Hello'
'Hello'
>>> "Hello"
'Hello'
>>> s='\u0048\u0065\u006c\u006c\u006f'
>>> s
'Hello'
>>> "Hello'world"
"Hello'world"
>>> 'Hello"world'
'Hello"world'

6.1.2 原始字符串

在 Python 中,以字母 r 或者 R 作为前缀的字符串,例如 r'...'和R'...',被称为原始字符串。

>>> s='hello\tworld\nPython\t3'
>>> print(s)
hello	world
Python	3
>>> s=r'hello\tworld\nPython\t3'
>>> print(s)
hello\tworld\nPython\t3

6.1.3 长字符串

使用三个单引号(''')或三个双引号(""")括起来.

>>> s='''
        xxx
        bfdzbd
        dfbd
        dfbd
        '''
>>> s
'\n        xxx\n        bfdzbd\n        dfbd\n        dfbd\n        '
>>> print(s)

        xxx
        bfdzbd
        dfbd
        dfbd

6.2 字符串与数字相互转换

6.2.1 将字符串转换为数字

>>> int("10")
10
>>> int("10.2")    #类型不同不能转换
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.2'
>>> float("10.2")
10.2
>>> int("ab")    #类型不同不能转换
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'ab'
>>> int("ab",16)    #按十六进制进行转换
171

6.2.2 将数字转换为字符串

>>> str(12)
'12'
>>> str(12.3)
'12.3'
>>> str(True)
'True'

6.3 格式化字符串

Python的字符串可通过占位符%、format ()方法和f-strings三种方式实现格式化输出。

6.3.1 占位符%

>>> name='xiaoqian'
>>> 'nihao,wojiao%s' % name
'nihao,wojiaoxiaoqian'
>>> age=20
>>> 'nihao,wojiao%s,今年%d岁'%(name,age)
'nihao,wojiaoxiaoqian,今年20岁'

6.3.2 format()方法

<字符串>.format (<参数列表>)

>>> name='小强'
>>> age=20
>>> '你好,我叫{},今年我{}岁了。'.format(name,age)
'你好,我叫小强,今年我20岁了。'
>>> '你好,我叫{1},今年我{0}岁了。'.format(age,name)    #可以指定参数序号顺序
'你好,我叫小强,今年我20岁了。'

format (方法还可以对数字进行格式化,包括保留n位小数、数字补齐和显示百分比。
①保留 n位小数。格式为“{:.nf}”
②数字补齐。格式为“{:m>nd]”,其中m 表示补齐的数字,n 表示补齐后数字的长度,>表示在原数字左侧进行补充。
③显示百分比。可以将数字以百分比形式显示。其格式为“{:.n%)”,其中n 表示保留的小数位。

>>> pi=3.1415
>>> '{:.2f}'.format(pi)
'3.14'
>>> num=1
>>> '{:0>3d}'.format(num)
'001'
>>> num
1
>>> num=0.1
>>> '{:.0%}'.format(num)
'10%'

6.3.3 f-strings

>>> addr='广州'
>>> f'欢迎来到{addr}'
'欢迎来到广州'
>>> name='小强'
>>> age=20
>>> gender='男'
>>> f'我的名字是{name},今年{age}岁,性别{gender}。'
'我的名字是小强,今年20岁,性别男。'

6.4 操作字符串

6.4.1 字符串拼接

>>> str_one='人生苦短,'
>>> str_two='我用python。'
>>> str_one+str_two
'人生苦短,我用python。'
>>> str_three=12
>>> str_one+str_three    #类型要一样
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> str_one+str(str_three)
'人生苦短,12'

6.4.2 字符串查找

str.find(sub[,start[,end]])查找子字符串,在索引start到end之间查找子字符串sub,如果找到,则返回最左端位置的索引;如果没有找到,则返回-1。

6.4.3 字符串替换

str.replace(old,new, count=None)字符串替换,new子字符串替换old子字符串。count参数指定了替换old子字符串的个数,count被省略,则替换所有old子字符串。

>>> word='我是小强,我今年20岁。'
>>> word.replace('我','他')
'他是小强,他今年20岁。'
>>> word.replace('我','他',1)
'他是小强,我今年20岁。'
>>> word.replace('他','你')
'我是小强,我今年20岁。'

 6.4.4 字符串分割

str.splite(sep=None,maxsplit=-1),使用sep子字符串分割字符串str,返回一个分割以后的字符串列表。maxsplit是最大分割次数,如果maxsplit被省略,则表示不限制分割次数。

>>> word="1 2 3 4 5"
>>> word.split()
['1', '2', '3', '4', '5']
>>> word="a,b,c,d,e"
>>> word.split(',')
['a', 'b', 'c', 'd', 'e']
>>> word.split(',',3)
['a', 'b', 'c', 'd,e']

 6.4.5 去除字符串两侧空格

str.strip(chars=None),一般用于去除字符串两侧的空格,参数chars用于设置要去除的字符,默认要去除的字符为空格

>>> word=' strip '
>>> word.strip()
'strip'
>>> word='**strip*'
>>> word.strip('*')
'strip'

 7.函数

7.1 定义函数

def 函数名([参数列表]):
        ["函数文档字符串"]
        函数体
        [return 语句]

>>> def rect_area():
    print("*" * 13)
    print('长方形面积:%d'%(12*2))
    print("*" * 13)
    
>>> rect_area    #函数地址
<function rect_area at 0x0391C270>
>>> rect_area()    #函数调用
*************
长方形面积:24
*************
>>> def rect_area(width,heigth):
    area=width*heigth
    return area

>>> print(rect_area(10,2))
20

 7.2 调用函数

函数名([参数列表])

>>> def rect_area():
    print("*" * 13)
    print('长方形面积:%d'%(12*2))
    print("*" * 13)
    
>>> rect_area    #函数地址
<function rect_area at 0x0391C270>
>>> rect_area()    #函数调用
*************
长方形面积:24
*************

7.3 函数参数传递

7.3.1 位置参数 

>>> def division(num_one,num_two):
    print(num_one/num_two)
    
>>> division(6,2)    #传递的参数与定义的参数一一对应
3.0

7.3.2 关键字参数 

>>> def division(num_one,num_two):
    print(num_one/num_two)
    
>>> division(num_one=10,num_two=2)
5.0

 7.3.3 默认参数

默认的参数要放到参数列表的最后面,否则会报错

>>> def info(name,age,sex='男'):
    print(f'姓名:{name}')
    print(f'年龄:{age}')
    print(f'性别:{sex}')
    
>>> info(name='xiao',age=20)
姓名:xiao
年龄:20
性别:男
>>> info('xiao',20)
姓名:xiao
年龄:20
性别:男
>>> info(name='xiao',age=20,sex='女')
姓名:xiao
年龄:20
性别:女
>>> def info(name,sex='男',age):
    print(f'姓名:{name}')
    print(f'年龄:{age}')
    print(f'性别:{sex}')
    
  File "<pyshell>", line 1
SyntaxError: non-default argument follows default argument

 7.3.4 不定长参数

def 函数名([formal_args,] *args, **kwargs):        #两个参数可以同时存在
        ["函数文档字符串"]
        函数体
        [return 语句]

①*args:接收的参数按原始方式保存

>>> def test(*args):
    print(args)
    
>>> test(1,2,3,'a','b')
(1, 2, 3, 'a', 'b')

②**kwargs:接收的参数按字段(键值对)方式保存

>>> def test(**kwargs):
    print(kwargs)
    
>>> test(a=1,b=2,c=3,d='a',e='b')
{'a': 1, 'b': 2, 'c': 3, 'd': 'a', 'e': 'b'}

 7.4 变量作用域

7.4.1 局部变量

>>> def use_var():
    name='python'
    print(name)
    
>>> use_var()
python
>>> print(name)   #name是局部变量,作用在use_var函数内
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
NameError: name 'name' is not defined
>>> 

 7.4.2 全局变量

>>> count=10    #定义一个全局变量
>>> def use_var():
    print(count)
    
>>> use_var()
10
>>> def use_var():
    global count        #声明count是全局变量,不声明会报错
    count+=10
    print(count)
    
>>> use_var()
20
>>> def use_var():
    count+=10
    print(count)
    
>>> use_var()
Traceback (most recent call last):
  File "<pyshell>", line 1, in <module>
  File "<pyshell>", line 2, in use_var
UnboundLocalError: local variable 'count' referenced before assignment
>>> print(count)
20

 7.5 函数特殊形式

7.5.1 匿名函数

匿名函数是一种不需要命名的函数。它通常用于简单的函数操作,可以在需要时直接定义和使用,而不需要为其分配一个特定的名称。匿名函数在很多编程语言中都存在,例如Python、JavaScript和Ruby等。在Python中,使用lambda关键字来定义匿名函数。

lambda [argl [,arg2,...argn]]:expression

[argl [,arg2,...argn]]:参数列表

expression:单一的函数表达式,用于实现简单的功能

>>> area=lambda a,h:(a*h)*0.5
>>> print(area)
<function <lambda> at 0x0380EBB8>
>>> print(area(3,4))
6.0

 7.5.2 递归函数

递归函数是指在函数的定义中使用函数自身的一种编程技巧。简单来说,递归函数是通过调用自身来解决问题的函数。

>>> def factorial(num):
    if num==1:
        return 1
    else:
        return num*factorial(num-1)
    
>>> factorial(5)
120

 7.6 常用内置函数

abs(): 计算绝对值,其参数必须是数字类型。
len(): 返回序列对象 (字符串、列表、元组等) 的长度。
map(): 根据提供的函数对指定的序列做映射。
help(): 用于查看函数或模块的使用说明。
ord(): 用于返回 Unicode 字符对应的码值。
chr():与 ord0功能相反,用于返回码值对应的 Unicode 字符。
filter(): 用于过滤序列,返回由符合条件的元素组成的新列表

>>> abs(-5)
5
>>> abs(3.14)
3.14
>>> len('python')
6
>>> ord('A')
65
>>> chr(65)
'A'
>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

>>> 
  • 13
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值