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))

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

相关推荐
沃斯堡&蓝鸟1 分钟前
DAY 29 异常处理
python
Direction_Wind4 分钟前
抓包的使用与讲解
python
职业码农NO.15 分钟前
智能体推理范式: Plan-and-Execute(规划与执行)
人工智能·python·数据分析·系统架构·知识图谱·agent·集成学习
爱笑的眼睛1129 分钟前
超越`cross_val_score`:深入剖析Scikit-learn交叉验证API的设计哲学与高阶实践
java·人工智能·python·ai
Ven%1 小时前
【AI大模型算法工程师面试题解析与技术思考】
人工智能·python·算法
天勤量化大唯粉1 小时前
枢轴点反转策略在铜期货中的量化应用指南(附天勤量化代码)
ide·python·算法·机器学习·github·开源软件·程序员创富
Swizard2 小时前
拒绝“狗熊掰棒子”!用 EWC (Elastic Weight Consolidation) 彻底终结 AI 的灾难性遗忘
python·算法·ai·训练
Spider赵毅2 小时前
python实战 | 如何使用海外代理IP抓取Amazon黑五数据
python·tcp/ip·php
月光技术杂谈2 小时前
基于Python的网络性能分析实践:从Ping原理到自动化监控
网络·python·性能分析·ping·时延·自动化监控
龘龍龙2 小时前
Python基础学习(四)
开发语言·python·学习