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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM