当前位置:   article > 正文

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

python2 字符串函数

6.字符串

6.1 字符串的表示方式

6.1.1 普通字符串

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

  1. >>> 'Hello'
  2. 'Hello'
  3. >>> "Hello"
  4. 'Hello'
  5. >>> s='\u0048\u0065\u006c\u006c\u006f'
  6. >>> s
  7. 'Hello'
  8. >>> "Hello'world"
  9. "Hello'world"
  10. >>> 'Hello"world'
  11. 'Hello"world'

6.1.2 原始字符串

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

  1. >>> s='hello\tworld\nPython\t3'
  2. >>> print(s)
  3. hello world
  4. Python 3
  5. >>> s=r'hello\tworld\nPython\t3'
  6. >>> print(s)
  7. hello\tworld\nPython\t3

6.1.3 长字符串

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

  1. >>> s='''
  2. xxx
  3. bfdzbd
  4. dfbd
  5. dfbd
  6. '''
  7. >>> s
  8. '\n xxx\n bfdzbd\n dfbd\n dfbd\n '
  9. >>> print(s)
  10. xxx
  11. bfdzbd
  12. dfbd
  13. dfbd

6.2 字符串与数字相互转换

6.2.1 将字符串转换为数字

  1. >>> int("10")
  2. 10
  3. >>> int("10.2") #类型不同不能转换
  4. Traceback (most recent call last):
  5. File "<pyshell>", line 1, in <module>
  6. ValueError: invalid literal for int() with base 10: '10.2'
  7. >>> float("10.2")
  8. 10.2
  9. >>> int("ab") #类型不同不能转换
  10. Traceback (most recent call last):
  11. File "<pyshell>", line 1, in <module>
  12. ValueError: invalid literal for int() with base 10: 'ab'
  13. >>> int("ab",16) #按十六进制进行转换
  14. 171

6.2.2 将数字转换为字符串

  1. >>> str(12)
  2. '12'
  3. >>> str(12.3)
  4. '12.3'
  5. >>> str(True)
  6. 'True'

6.3 格式化字符串

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

6.3.1 占位符%

  1. >>> name='xiaoqian'
  2. >>> 'nihao,wojiao%s' % name
  3. 'nihao,wojiaoxiaoqian'
  4. >>> age=20
  5. >>> 'nihao,wojiao%s,今年%d岁'%(name,age)
  6. 'nihao,wojiaoxiaoqian,今年20岁'

6.3.2 format()方法

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

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

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

  1. >>> pi=3.1415
  2. >>> '{:.2f}'.format(pi)
  3. '3.14'
  4. >>> num=1
  5. >>> '{:0>3d}'.format(num)
  6. '001'
  7. >>> num
  8. 1
  9. >>> num=0.1
  10. >>> '{:.0%}'.format(num)
  11. '10%'

6.3.3 f-strings

  1. >>> addr='广州'
  2. >>> f'欢迎来到{addr}'
  3. '欢迎来到广州'
  4. >>> name='小强'
  5. >>> age=20
  6. >>> gender='男'
  7. >>> f'我的名字是{name},今年{age}岁,性别{gender}。'
  8. '我的名字是小强,今年20岁,性别男。'

6.4 操作字符串

6.4.1 字符串拼接

  1. >>> str_one='人生苦短,'
  2. >>> str_two='我用python。'
  3. >>> str_one+str_two
  4. '人生苦短,我用python。'
  5. >>> str_three=12
  6. >>> str_one+str_three #类型要一样
  7. Traceback (most recent call last):
  8. File "<pyshell>", line 1, in <module>
  9. TypeError: can only concatenate str (not "int") to str
  10. >>> str_one+str(str_three)
  11. '人生苦短,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子字符串。

  1. >>> word='我是小强,我今年20岁。'
  2. >>> word.replace('我','他')
  3. '他是小强,他今年20岁。'
  4. >>> word.replace('我','他',1)
  5. '他是小强,我今年20岁。'
  6. >>> word.replace('他','你')
  7. '我是小强,我今年20岁。'

 6.4.4 字符串分割

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

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

 6.4.5 去除字符串两侧空格

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

  1. >>> word=' strip '
  2. >>> word.strip()
  3. 'strip'
  4. >>> word='**strip*'
  5. >>> word.strip('*')
  6. 'strip'

 7.函数

7.1 定义函数

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

  1. >>> def rect_area():
  2. print("*" * 13)
  3. print('长方形面积:%d'%(12*2))
  4. print("*" * 13)
  5. >>> rect_area #函数地址
  6. <function rect_area at 0x0391C270>
  7. >>> rect_area() #函数调用
  8. *************
  9. 长方形面积:24
  10. *************
  11. >>> def rect_area(width,heigth):
  12. area=width*heigth
  13. return area
  14. >>> print(rect_area(10,2))
  15. 20

 7.2 调用函数

函数名([参数列表])

  1. >>> def rect_area():
  2. print("*" * 13)
  3. print('长方形面积:%d'%(12*2))
  4. print("*" * 13)
  5. >>> rect_area #函数地址
  6. <function rect_area at 0x0391C270>
  7. >>> rect_area() #函数调用
  8. *************
  9. 长方形面积:24
  10. *************

7.3 函数参数传递

7.3.1 位置参数 

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

7.3.2 关键字参数 

  1. >>> def division(num_one,num_two):
  2. print(num_one/num_two)
  3. >>> division(num_one=10,num_two=2)
  4. 5.0

 7.3.3 默认参数

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

  1. >>> def info(name,age,sex='男'):
  2. print(f'姓名:{name}')
  3. print(f'年龄:{age}')
  4. print(f'性别:{sex}')
  5. >>> info(name='xiao',age=20)
  6. 姓名:xiao
  7. 年龄:20
  8. 性别:男
  9. >>> info('xiao',20)
  10. 姓名:xiao
  11. 年龄:20
  12. 性别:男
  13. >>> info(name='xiao',age=20,sex='女')
  14. 姓名:xiao
  15. 年龄:20
  16. 性别:女
  17. >>> def info(name,sex='男',age):
  18. print(f'姓名:{name}')
  19. print(f'年龄:{age}')
  20. print(f'性别:{sex}')
  21. File "<pyshell>", line 1
  22. SyntaxError: non-default argument follows default argument

 7.3.4 不定长参数

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

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

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

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

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

 7.4 变量作用域

7.4.1 局部变量

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

 7.4.2 全局变量

  1. >>> count=10 #定义一个全局变量
  2. >>> def use_var():
  3. print(count)
  4. >>> use_var()
  5. 10
  6. >>> def use_var():
  7. global count #声明count是全局变量,不声明会报错
  8. count+=10
  9. print(count)
  10. >>> use_var()
  11. 20
  12. >>> def use_var():
  13. count+=10
  14. print(count)
  15. >>> use_var()
  16. Traceback (most recent call last):
  17. File "<pyshell>", line 1, in <module>
  18. File "<pyshell>", line 2, in use_var
  19. UnboundLocalError: local variable 'count' referenced before assignment
  20. >>> print(count)
  21. 20

 7.5 函数特殊形式

7.5.1 匿名函数

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

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

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

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

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

 7.5.2 递归函数

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

  1. >>> def factorial(num):
  2. if num==1:
  3. return 1
  4. else:
  5. return num*factorial(num-1)
  6. >>> factorial(5)
  7. 120

 7.6 常用内置函数

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

  1. >>> abs(-5)
  2. 5
  3. >>> abs(3.14)
  4. 3.14
  5. >>> len('python')
  6. 6
  7. >>> ord('A')
  8. 65
  9. >>> chr(65)
  10. 'A'
  11. >>> help(len)
  12. Help on built-in function len in module builtins:
  13. len(obj, /)
  14. Return the number of items in a container.
  15. >>>
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/999882
推荐阅读
相关标签
  

闽ICP备14008679号