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

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

相关推荐
❁满城风絮*10 小时前
Claude Code 学习总结
python·agent·claude
维克兜率天12 小时前
【维克】复合型CTA:趋势+套利的双轮驱动
python·学习方法
伞伞悦读12 小时前
【第76期】两张3行表左连接变5行:主键、validate与未匹配排查完整教程
人工智能·python
用户83562907805113 小时前
使用 Python 在 Excel 中添加和自定义迷你图
后端·python
用户83562907805113 小时前
使用 Python 在 Excel 图表中添加趋势线与回归方程
后端·python
特立独行的猫A14 小时前
一份 Markdown 发十个平台:cspub 一稿多投
java·后端·python
深蓝AI14 小时前
HTTPX 超时 1 秒,接口为何还能跑 2.4 秒?
python
CyrusYiVPP14 小时前
哪个用户会再来买?RFM模型+plotly画出用户分层,数据分析实战第2期
人工智能·python
李帅51516 小时前
用 CPU 做发票识别:从 OCR 文本行到结构化明细表的 4 个硬骨头
python
happylifetree16 小时前
Python79:核心语法-面向对象基础-实例方法
python