python字符串练习与答案

1.定义两个变量x,y,分别赋值3,5,用eval()函数计算x的y次方的值。

复制代码
x = 3

y = 5

print(eval('x**y'))

2.输入我出生年份和月份,分别赋给变量year和month,然后用format()方法输出。

格式要求:宽度20,居中对齐,-号填充

复制代码
year = int(input('请输入你的出生年份:'))

month = int(input('请输入你的出生月份:'))

print('我出生于{:-^10}年{:-^10}月'.format(year,month))

3.输入浮点数3.14159,屏幕输出¥¥¥¥¥¥3.14 (格式要求:宽度10,右对齐,保留两位小数,¥号填充。

复制代码
num = 3.14159

print('{:¥>10.2f}'.format(num))

4.已知一个字符串为 "hello_world_yoyo",请用split()方法得到一个"hello","world","yoyo"

复制代码
string = 'hello_world_yoyo'

print (string.split('_'))

5.有个列表 "hello", "world", "python",请用join()方法列表里面的字符串联起来,得到字符串 "hello_world_python"。

复制代码
symbol = '_'

a = ['hello','world','python']

print(symbl.join(a))

6.把字符串 "We are happy." 中的每个空格替换成"%20",输出:"We%20are%20happy."。

复制代码
str = 'we are happy'

print(str.replace(' ','%20'))

7.假设我们给fruits 赋值列表'apple', 'banana', 'orange', 'apple', 'grape', 'apple',我们怎么统计列表中apple出现的次数(用count()函数)。

复制代码
fruits = ['apple','banana','orange','apple','grape', 'apple']

a = fruits.count('apple')

print(a)

8.假设我们给text 赋值字符串"Python is a powerful programming language. Python is widely used in web development, data analysis, and artificial intelligence."我们怎么统计字符串中Python出现的次数(用count()函数)。

复制代码
text = "Python is a powerful programming language. Python is widely used in web development, data analysis, and artificial intelligence."

b = text.count('Python')

print(b)

9.用input()输入你的零花钱,用变量lhq存储;输入你每天的平均消费,用变量xf存储;输入本月的天数,用户变量x存储。然后计算出你本月还剩多少余额,存为变量yu,使用format()函数输出'本月我还剩余元。

复制代码
pockt_money = int(input('请输入你的零花钱:'))

consumption = int(input('请输入你的消费金额:'))

month_day = int(input('请输入当月天数:'))

remaining_sum = int(pockt_money-consumption*month_day)

print('本月我还剩余{}元'.format(remaining_sum))

习题来源于其他博主的文章,本文只是记录解题过程!

相关推荐
梦想不只是梦与想几秒前
Python 中的 match-case(模式匹配)
python·match-case
郝同学今天有进步吗3 分钟前
构建 LangGraph Code Review Agent(四):文件过滤与 AnalysisPackage 分包
git·python·ai·code review
a1117769 分钟前
基于PyTorch的动物图像识别系统 开源
人工智能·pytorch·python
qetfw15 分钟前
MWU:Vue 3 + FastAPI 的 MaaFramework 跨平台 WebUI 源码
前端·vue.js·python·fastapi·开源项目·效率工具
测试老哥22 分钟前
接口自动化测试分层设计与实践总结
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
大模型码小白1 小时前
企业级检索增强后端集成:Java 服务如何管理知识库版本
java·服务器·开发语言·人工智能·python·microsoft
农村小镇哥1 小时前
Python3开发快速获取图片的文字
开发语言·python
FriendshipT1 小时前
Ultralytics:解读Proto模块
人工智能·pytorch·python·深度学习·目标检测
zhiSiBuYu05171 小时前
Python3 循环语句新手实战指南
python
ShirleyWang0121 小时前
Day02 K3s NGF(Nginx Gateway Fabric)单 Worker 环境网关更新与故障处置 SOP
linux·服务器·python·k8s·k3s