Python考试复习--day3

1.统计字符串个数

python 复制代码
n=input()
z=0
s=0
k=0
o=0
for i in n:
    if i.isalpha():
        z=z+1
    elif i.isnumeric():
        s=s+1
    elif i.isspace():
        k+=1
    else:
        o+=1
print('字母有{}个,数字有{}个,空格有{}个,其他字符{}个'.format(z,s,k,o))

2.分类统计字符

python 复制代码
n=input()
x=0
d=0
s=0
k=0
o=0
for i in n:
    if i.islower():
        x+=1
    elif i.isupper():
        d+=1
    elif i.isnumeric():
        s+=1
    elif i.isspace():
        k+=1
    else:
        o+=1
print(x,d,s,k,o)        
#print('{} {} {} {} {}'.format(x,d,s,k,o))

3.大小写转换

python 复制代码
import string 
n=input()
for i in n:
    if i in string.ascii_lowercase: #注意别忘记case
        print(i.upper(),end='')
    elif i in string.ascii_uppercase:
        print(i.lower(),end='')
    else:
        print(i,end='')

**import string(别忘写!!!)**中大写字母转小写字母、小写字母转大写字母的用法:

upper()

lower()

string.ascii_lowercase #注意别忘记case!!!

string.ascii_uppercase

python中end=''的用法

在print()输出语句后面加入end='',以防止print()输出语句自动换行 ,通过end=' '将输出结果放在同一行,输出结果之间的间隔数取决于引号间的空格数。

第一种,不加end='',会自动换行
第二种,加end='',不换行

4.判断字符串结尾

python 复制代码
n=input()
if n[-2:] in 'PY':
    print('YES')
else:
    print('NO')

5.反转一个整数

python 复制代码
n=input()
n1=n[::-1] #反转

#负数情况
if n1[-1] in '-':
    n1='-'+n1[:-1].strip('0') #加'-',并且删除最后的负数和前后的0
#正数情况
else:
    n1=n1.strip('0')# 去掉前后的0
print(n1)

strip()函数

Python字符串方法之一,**用于处理字符串的前导和尾随空白字符。**它返回一个新字符串,该字符串是原始字符串去除前导和尾随空格(包括空格、制表符、换行符等)后的结果。

6.替换中文数字

样例重点!!!

python 复制代码
s=input()
sIn='零一二三四五六七八九'
sOut='0123456789'
t=str.maketrans(sIn,sOut)
print(s.translate(t))

Python maketrans() 方法用于给 translate() 方法创建 字符映射转换

str.maketrans(需要转换的,转换的目标)

一般 maketrans() 方法需要配合 translate() 方法一起使用。
Python translate() 方法根据 maketrans() 方法给出的字符映射转换表转换 字符串中的字符

输入名.translate(table)--table字符映射转换表

相关推荐
曲幽2 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程6 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪7 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook7 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田20 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪1 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽1 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战1 天前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋1 天前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python