Python字符串练习

时间:2021-09-11 02:13:04
#1.执行Python的两种方式
# python
# python 1.py

#2.简叙位,字节的关系
# 8位1字节

#3.ascii,unicode ,utf-8,gbk的关系
# ascii
# unicode
# utf-8
#
4."李姐" 用utf-8和gbk编码所占的位数
# utf-8:6
# gbk:4
#
5.Python单行注释和多行注释
# #
# '''
#
# '''
#
6.n = 5 该变量最少用多少个二进制位表示
# n = 5
# print(n.bit_length())
# 3个
#
7.布尔值分别有什么
# True
# False
#
8.阅读代码,写出执行结果
# a = "alex"
# b = a.capitalize()
# print(a)
# print(b)
# a == alex
# b == Alex
#
9.name 完成以下功能
name = " sdxxxXfXAXA "
#去除前后空格
v1 = name.strip()
print(v1)
#检查开始于结尾
v2 = v1.startswith("sd")
print(v2)
v3
= v1.endswith("AA")
print(v3)
#字符串替换
v4_1 = v1.replace("xXf","RRR")
#对应字符串替换
v4_2 = v1.maketrans("xXf","RRR")
v4_3
= v1.translate(v4_2)
print(v4_1)
print(v4_3)
#分割字符串
v5_1 = v1.split("X")
v5_2
= v1.partition("X")
print(v5_1)
print(v5_2)
#迭代循环字符串
n = 0
while n < len(v1):
print(n,v1[n],"\t",end="")
n
+=1
print()
#用下划线连接字符串中的每一个元素
l = "_"
v6
= l.join(v1)
print(v6)
#用户输入 实现简单计算
#
n1 = int(input("输入第一个数字:"))
#
n2 = int(input("输入第二个字符串:"))
#
n3 = n1+n2
#
print(n1,"+",n2,n3)

# s1 = input("请输入一个整数加法:")
s1 = "1+6+7+5+9+4+2+7+9+4+9+4+65+454+818"
print(s1,end="")
sr
= s1.split("+")
result
= 0
count
= 0
while result <len(sr):
count
+= int(sr[result])
result
+=1
print("=",count)
#计算字符串中数字的个数
string = "2134Df犯得上"
count1,int1,str1
= 0,0,0
while count1 < len(string):
if string[count1].isnumeric() == True:
int1
+= 1
count1
+=1
str1
= len(string)-int1
print(string,"\n数字:",int1,"\t字母和汉字:",str1)

运行结果

Python字符串练习