可变字符串
在 Python 中,字符串属于不可变对象,不支持原地修改,如果需要修改其中的值,将智能创建新的字符串对象。但是,经常我们确实需要原地修改字符串,可以使用 io.StringIO对象或 array 模块。
io.StringIO用法示例:
>>> import io
>>> a = 'hello,Python!'
>>> sio = io.StringIO(a)
>>> sio
<_io.StringIO object at 0x0000022C28C9B040>
>>> sio.getvalue()
'hello,Python!'
>>> sio.seek(8) #将改动指针调到位置8
8
>>> sio.write('i')
1
>>> sio.getvalue()
'hello,Pyihon!'
>>> sio.write('t') #改动指针会在改动行动发生后自动右移动改动输入量的位置
1
>>> sio.getvalue()
'hello,Pyiton!'
>>> sio.seek(8)
8
>>> sio.write('th')
2
>>> sio.getvalue()
'hello,Python!'
>>> sio.seek(12)
12
>>> sio.write('123321')
6
>>> sio.getvalue()
'hello,Python123321'
本章实操作业
1. 使用 python 表示数学式:
2. 从控制台输入用户的月薪,进行运算计算出年薪。打印输出用户的年薪
3. 使用字符串复制,用计算机打印出“爱你一百遍”,打印 100 次
4. 将”to be or not to be”字符串倒序输出
5. 将”sxtsxtsxtsxtsxt”字符串中所有的 s 输出
6. 判断如下输出结果,并文字解释原因:
>>> a = "abd_33"
>>> b = "abd_33"
>>> c = "dd#"
>>> d = "dd#"
>>> a is b #输出 true or false?
>>> c is d #输出 true or false?
7. 写出如下代码打印的结果:
>>> c = "名字是{name},年龄是{age}"
>>> c.format(age=17,name='小明')
我的解答,源码:
#1
x = y = a = b = 2
sxs = (5 + 10 * x) / 5 - 13 * (y - 1) * (a + b) / x + 9 * (5 / x + (12 + x) /y)
print(sxs)
#对比口算结果,验算通过。
#题目:从控制台输入用户的月薪,进行运算计算出年薪。打印输出用户的年薪
'''
#2
monthly_salary = input('请输入月薪:')
annual_salary = 12 * float(monthly_salary)
print(('年薪为:{}').format(annual_salary))
'''
'''
#2 格式2
print(('年薪为:{}').format(12 * float(input('请输入月薪:'))))
'''
'''
#2 效率比较
import time
time01 = time.time()
monthly_salary = '3000'
annual_salary = 12 * float(monthly_salary)
print(('年薪为:{}').format(annual_salary))
time02 = time.time()
print(time02 - time01)
time03 = time.time()
print(('年薪为:{}').format(12 * float('3000')))
time04 = time.time()
print(time04 - time03)
'''
#3
print('爱你100遍\n' * 100)
#4
a = 'to be or not to be'
print(a[::-1])
#5
a = 'sxtsxtsxtsxtsxt'
print(a[0::3])
#6
a = "abd_33"
b = "abd_33"
c = "dd#"
d = "dd#"
print(a is b) #输出 true or false?
print(c is d) #输出 true or false?
'''
第6题的答案应该是:
如果交互模式下,第1个为True,第2个为False。因为Python 支持字符串驻留机制,
对于符合标识符规则的字符串(仅包含下划线(_)、字母和数字)会启用字符串驻
留机制驻留机制。
如果是作为文件运行,则两个均为True。因为与数的保存机制一样,解释器对运行进行
了优化,不符合标识符规则的字符串只要一样也是存在同一地址。
'''
#7
'名字是小明,年龄是17’