字符串
使用引號(單引號、雙引號、三引號)引起來的內容就是字符串。 字符串官方定義:元素以引號包圍不可修改的有序序列。 注: 1.不可修改:字符串中的內容一旦定義後就不能修改。 2.有序序列:即成員(字符)有序排列,可通過下標訪問。
**字符串索引:**字符串中每一個個體我們稱之爲字符或者元素。索引指的是字符的下標。 字符串索引正序從0開始,倒序從1開始。
字符串切片字符串的切片指的是從字符串中複製出一份指定的內容,存儲在另外一個變量 中,不會對原字符串進行修改。 切片格式:[起始索引:結束索引:[步長]]
注: (1).步長可以省略,默認爲1。 (2).包括開頭不包含結尾。
例:
s ="hello world"
s2=s[2:4:1]
print(s2)
s3 = s[0:8]
print(s3)
s4 = s[::2]
print(s4)
s5 = s[:4:2]
print(s5)
s6 =s[4::1]
print(s6)
s7 =s[1:8:-1]
print(s7)
s10 = s[0:8:-1]
print(s10)
hello world
s11= s[8:1:-1]
print(s11)
結果:
ll
hello wo
hlowrd
hl
o world
row oll
字符串函數
例:
s3="and-jd-ddd"
print(s3.partition("-"))
print(s3.split("n"))
s4="dsf\ndd\ndds"
print(s4.splitlines())
print(s4.split("\n"))
s5="dingding"
print(s5.replace("d","n"))
s ="hello world"
# # print(s.rindex("d"))
#
print(s.center(30,"*"))
print(s.ljust(30,"*"))
print(s.rjust(30,"*"))
#
結果:
('and', '-', 'jd-ddd')
['a', 'd-jd-ddd']
['dsf', 'dd', 'dds']
['dsf', 'dd', 'dds']
ningning
*********hello world**********
hello world*******************
*******************hello world