Python字符串更新

Python字符串更新:截取字符串的某一部分 和 其他字符串进行拼接。

  注:可以修改字符串的值,但修改的不是内存中的值,而是创建新的字符串。

1.使用字符串常量进行更新:

# 使用字符串常量
strs = "hello,hey"
print(strs[:6] + "world.")
# hello,world.

2.使用切片操作(不包含结尾 stop)进行更新:

strs = "hello,hey"
py = "Tom,Jerry"

s_1 = strs[:6] + py[:3]
print(strs[:6])
# hello,
print(py[:3])
# Tom
print("更新后的字符串:",s_1)
# 更新后的字符串: hello,Tom

strs = "hello,hey"
py = "Tom,Jerry"

s_2 = strs[:5] + py[3:]

print(strs[:5])
# hello
print(py[3:])
# ,Jerry
print("更新后的字符串:",s_2)
# 更新后的字符串: hello,Jerry

切片的其他操作:

# strs = "ABCDEFG"
# print(strs[:4:2])
# # AC
#
# print(strs[2:6])
# # CDEF
#
# print(strs[2:6:2])
# # CE
#
# # 不包含结束位置
# print(strs[6:2:-1])
# # GFED
#
# print(strs[6:2:-2])
# # GE

修改字符串:

# 修改字符串,将 world 修改为 python
strs = "hello,world"
strs = strs[:6] + "python"
print("更新后的字符串:{0}".format(strs))
# 更新后的字符串:hello,python

2020-02-08