【从零学习python 】 Python中的字符串操作与函数基本使用
  LyJBRSvfEdxZ 2023年11月13日 23 0

执行字符串

使用Python内置的eval函数,可以执行字符串里的Python代码。使用这种方式,可以将字符串转换成为其他类型的数据。

x = '1+1'
print(eval(x))  # 2
print(type(eval(x)))  # <class 'int'>

y = '{"name":"zhangsan","age":18}'
print(eval(y))
print(type(eval(y)))  # <class 'dict'>

print(eval('1 > 2'))  # False

eval('input("请输入您的姓名:")')

转换成为字符串

JSON(JavaScript Object Notation, JS对象简谱)是一种轻量级的数据交换格式,它基于 ECMAScript 的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。JSON本质是一个字符串

JSON的功能强大,使用场景也非常的广,目前我们只介绍如何使用Python的内置JSON模块,实现字典、列表或者元组与字符串之间的相互转换。

使用json的dumps方法,可以将字典、列表或者元组转换成为字符串。

import json

person = {'name': 'zhangsan', 'age': 18}
x = json.dumps(person)
print(x)  # {"name": "zhangsan", "age": 18}
print(type(x))  # <class 'str'>

nums = [1, 9, 0, 4, 7]
y = json.dumps(nums)
print(y)  # [1, 9, 0, 4, 7]
print(type(y)) # <class 'str'>

words = ('hello','good','yes')
z = json.dumps(words)
print(z) # ["hello", "good", "yes"]
print(type(z)) # <class 'str'>

使用json的loads方法,可以将格式正确的字符串转换成为字典、列表。

x = '{"name": "zhangsan", "age": 18}'
person = json.loads(x)
print(person)  # {'name': 'zhangsan', 'age': 18}
print(type(person)) # <class 'dict'>

y = '[1, 9, 0, 4, 7]'
nums = json.loads(y)
print(nums) # [1, 9, 0, 4, 7]
print(type(nums)) # <class 'list'>

字符串、列表、元组、字典和集合的共同点

字符串、列表、元组、字典和集合,它们有很多相同点,都是由多个元素组合成的一个可迭代对象,它们都有一些可以共同使用的方法。

算数运算符

在Python里,常见的算数运算符,有一些可以使用于可迭代对象,它们执行的结果也稍有区别。

运算符 Python 表达式 结果 描述 支持的数据类型
+ [1, 2] + [3, 4] [1, 2, 3, 4] 合并 字符串、列表、元组}
- {1,2,3,4} - {2,3} {1,4} 集合求差集 集合
* ['Hi!'] * 4 ['Hi!', 'Hi!', 'Hi!', 'Hi!'] 复制 字符串、列表、元组
in 3 in (1, 2, 3) True 元素是否存在 字符串、列表、元组、字典
not in 4 not in (1, 2, 3) True 元素是否不存在 字符串、列表、元组、字典

+

加法运算符可以用于字符串、列表和元组,用来拼接多个可迭代对象,不能用于字典和集合。

>>> "hello " + "world"
'hello world'
>>> [1, 2] + [3, 4]
[1, 2, 3, 4]
>>> ('a', 'b') + ('c', 'd')
('a', 'b', 'c', 'd')

-

减法只能用于集合里,用来求两个集合的差集。

>>> {1, 6, 9, 10, 12, 3} - {4, 8, 2, 1, 3}
{9, 10, 12, 6}

*

加法运算符可以用于字符串、列表和元组,用来将可迭代对象重复多次,同样不能用于字典和集合。

>>> 'ab' * 4
'ababab'
>>> [1, 2] * 4
[1, 2, 1, 2, 1, 2, 1, 2]
>>> ('a', 'b') * 4
('a', 'b', 'a', 'b', 'a', 'b', 'a', 'b')

in

in和not in成员运算符可以用于所有的可迭代对象。但是需要注意的是,in 和 not in 在对字典进行判断时,是查看指定的key是否存在,而不是value.

>>> 'llo' in 'hello world'
True
>>> 3 in [1, 2]
False
>>> 4 in (1, 2, 3, 4)
True
>>> "name" in {"name":"chris", "age":18}
True

遍历

通过for ... in ... 我们可以遍历字符串、列表、元组、字典、集合等可迭代对象。

字符串遍历

a_str = "hello world"
for char in a_str:
    print(char,end=' ')

列表遍历

a_list = [1, 2, 3, 4, 5]
for num in a_list:
    print(num,end=' ')

元组遍历

a_turple = (1, 2, 3, 4, 5)
for num in a_turple:
    print(num,end=" ")

带下标的遍历

可迭代对象都可以使用enumerate内置类进行包装成一个enumerate对象。对enumerate进行遍历,可以同时得到一个可迭代对象的下标和元素。

nums = [12, 9, 8, 5, 4, 7, 3, 6]

# 将列表nums包装成enumerate对象
for i, num in enumerate(nums): # i表示元素下标,num表示列表里的元素
    print('第%d个元素是%d' % (i, num))

函数介绍

什么是函数

请看如下代码:

print("                            _ooOoo_  ")
print("                           o8888888o  ")
print("                           88  .  88  ")
print("                           (| -_- |)  ")
print("                            O\\ = /O  ")
print("                        ____/`---'\\____  ")
print("                      .   ' \\| |// `.  ")
print("                       / \\||| : |||// \\  ")
print("                     / _||||| -:- |||||- \\  ")
print("                       | | \\\\\\ - /// | |  ")
print("                     | \\_| ''\\---/'' | |  ")
print("                      \\ .-\\__ `-` ___/-. /  ")
print("                   ___`. .' /--.--\\ `. . __  ")
print("                ."" '< `.___\\_<|>_/___.' >'"".  ")
print("               | | : `- \\`.;`\\ _ /`;.`/ - ` : | |  ")
print("                 \\ \\ `-. \\_ __\\ /__ _/ .-` / /  ")
print("         ======`-.____`-.___\\_____/___.-`____.-'======  ")
print("                            `=---='  ")
print("  ")
print("         .............................................  ")
print("                  佛祖镇楼                  BUG辟易  ")
print("          佛曰:  ")
print("                  写字楼里写字间,写字间里程序员;  ")
print("                  程序人员写程序,又拿程序换酒钱。  ")
print("                  酒醒只在网上坐,酒醉还来网下眠;  ")
print("                  酒醉酒醒日复日,网上网下年复年。  ")
print("                  但愿老死电脑间,不愿鞠躬老板前;  ")
print("                  奔驰宝马贵者趣,公交自行程序员。  ")
print("                  别人笑我忒疯癫,我笑自己命太贱;  ")
print("                  不见满街漂亮妹,哪个归得程序员?"

想一想:

如果一个程序在不同的地方需要输出“佛祖镇楼”,程序应该怎样设计?

if 条件1:
    输出‘佛祖镇楼’

...(省略)...

if 条件2:
    输出‘佛祖镇楼’

...(省略)...

如果需要输出多次,是否意味着要编写这块代码多次呢?

小总结: 如果在开发程序时,需要某块代码多次执行。为了提高编写的效率以及更好的维护代码,需要把具有独立功能的代码块组织为一个小模块,这就是函数。

函数定义和调用

一、定义函数

定义函数的格式如下:

def 函数名():
    代码

示例:

# 定义一个函数,能够完成打印信息的功能
def printInfo():
    print('------------------------------------')
    print('         人生苦短,我用Python')
    print('------------------------------------')

二、调用函数

定义了函数之后,就相当于有了一个具有某些功能的代码,想要让这些代码能够执行,需要调用它。

调用函数很简单的,通过 函数名() 即可完成调用。

# 定义完函数后,函数是不会自动执行的,需要调用它才可以
printInfo()

三、注意:

函数定义好以后,函数体里的代码并不会执行,如果想要执行函数体里的内容,需要手动的调用函数。 每次调用函数时,函数都会从头开始执行,当这个函数中的代码执行完毕后,意味着调用结束了。 当然了如果函数中执行到了return也会结束函数。

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月13日 0

暂无评论

推荐阅读
  fwjWaDlWXE4h   16天前   20   0   0 Python
LyJBRSvfEdxZ