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 分钟前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞2 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽4 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程9 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪9 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook9 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python