实验目的与要求:
1.掌握转义字符的使用方法;
2.掌握字符串的输入输出使用方法;
3.掌握格式化操作符的方法;
4.掌握字符串内建函数的作用。
实验内容:
1、子串的应用。获取星期字符串,程序读入一个表示星期几的数字(1~7),输出对应的星期字符串名称。例如,输入3,返回“星期三”。
代码如下:
weekstr ="星期一星期二星期三星期四星期五星期六星期日"
weekid =eval(input("请输入星期数字(1-7): "))
pos=(weekid-1)*3
print(weekstr[pos:pos+3])
2、内置的字符串处理函数
函数 | 描述 |
len(x) | 返回字符串x的长度,也可返回其他组合数据类型元素个数 |
str(x) | 返回任意类型x所对应的字符串形式 |
chr(x) | 返回Unicode编码x对应的单字符 |
ord(x) | 返回单字符表示的Unicode编码 |
hex(x) | 返回整数x对应十六进制数的小写形式字符串 |
oct(x) | 返回整数x对应八进制数的小写形式字符串 |
>>> print(ord(x))
97
>>> print(chr(97))
a
>>> print(chr(5))
#方框
>>> x=2156
>>> print(hex(x))
0x86c
>>> print(oct(x))
0o4154
>>> print(bin(x))
0b100001101100
3、字符串运算符
(1)*:重复一个字符串
>>> s='abc'
>>> s*3
'abcabcabc'
(2)in/not in:判断一个字符串是否在另一个字符串中
>>> s='abc'
>>> x='a'
>>> x in s
True
>>> y='1'
>>> y not in s
True
(3)is/ is not:判断两个字符串是否是同一个对象
>>> x='1'
>>> y='1'
>>> id(x)==id(y)
True
>>> x is y
True
>>> x is not y
False
(4)关系运算符:通过字符串中对应的字符的ASCII码决定字符串的大小
>>> s1='abc'
>>> s2='0x2'
>>> s1>s2
True
>>> s1<s2
False
4、遍历字符串
(1)for…in 字符串名
>>> s1='abc'
>>> for i in s1: #按字符遍历
print(i,end=' ')
a b c
(2)for…in range(len(字符串))
>>> s1='abc'
>>> for i in range(len(s1)): #按索引(下标)遍历
print(s1[i],end=' ')
a b c
5、转换字符串
(1)capitalize():返回第一个单词首字母大写的新字符串
>>> s1='abc'
>>> print(s1.capitalize())
Abc
(2)title():返回每个单词首字母大写的新字符串
>>> s='hello,python is good.'
>>> print(s.title())
Hello,Python Is Good.
(3)swapcase():返回小写字母变成大写字母,大写字母变成小写字母后的新字符串
>>> s='Hello,Python Is Good.'
>>> print(s.swapcase())
hELLO,pYTHON iS gOOD.
(4)replace(old,new[,count]):返回用new替换old后的新字符串,count可选,若指定了count,则new替换old最多count次。
>>> s='red yellow blue pind red black red white.'
>>> print(s.replace('red','红色',2))
红色 yellow blue pind 红色 black red white.
>>> print(s.replace('red','红色'))
红色 yellow blue pind 红色 black 红色 white.
6、time模块的使用
(1)制作文本进度条
import time
scale = 10
print("——----执行开始-―—---")
for i in range (scale+1):
a, b ='**'* i,'..' * (scale - i)
c =(i/scale)*100
print("%{:^3.0f}[{}-->{}]".format (c, a, b))
time.sleep (0.1)
print ( "—-----执行结束------")
(2)单行动态刷新
import time
for i in range(101):
print("\r{:2}%".format(i),end="")
time.sleep(0.05)
练习题
1.编写程序,根据读入的字符值以及三角形的高,输出以该字符为填充字符的等腰三角形。例如,填充字符为A、高度为5的等腰三角形如下:
for i in range(1,5):
for j in range(1,5-i+1):
print(' ',end='')
for k in range(1,2*i-1+1):
print('*',end='')
print()
2..编写程序,某工地需要搬运砖块,已知男人一人搬3块,女人一人搬2块,小孩两人搬1块。用45人正好搬45块砖,问有多少种搬法?
count = 0
# 遍历男人、女人和小孩的人数
for men in range(16): # 最多有15个男人(因为3*15=45)
for women in range(23): # 最多有22个女人(因为2*22=44,不足45)
children = 45 - men - women
total_bricks = 3 * men + 2 * women + 0.5 * children
if total_bricks == 45:
count += 1
print(f"共有 {count} 种搬砖方式。")
3.编写程序,根据读入的字符值及菱形的边长,输出以该字符为填充字符的菱形。
def print_diamond(char, size):
# 上半部分菱形
for i in range(size):
print(" " * (size - i - 1) + char * (2 * i + 1))
# 下半部分菱形
for i in range(size - 2, -1, -1):
print(" " * (size - i - 1) + char * (2 * i + 1))
char = input("请输入填充字符:")
size = int(input("请输入菱形的边长:"))
print_diamond(char, size)
4.编写程序,从键盘输入10个数,要求用“冒泡法”按由小到大的顺序输出这10个数,并用“<”连接。
# 冒泡排序函数
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# 主程序
nums = []
for i in range(10):
num = int(input(f"请输入第 {i+1} 个数: "))
nums.append(num)
bubble_sort(nums)
output_str = " < ".join(map(str, nums))
print("按由小到大的顺序输出这10个数:")
print(output_str)