1. 程式人生 > >元組、列表、字串以及切片的一些小操作記錄

元組、列表、字串以及切片的一些小操作記錄

元組操作

  • 元組可以使用下標索引來訪問元組中的值
  • 元組中的元素值不允許修改和刪除

切片操作:

print str[0:3] #擷取第一位到第三位的字元
print str[:] #擷取字串的全部字元
print str[6:] #擷取第七個字元到結尾
print str[:-3] #擷取從頭開始到倒數第三個字元之前
print str[2] #擷取第三個字元
print str[-1] #擷取倒數第一個字元
print str[::-1] #創造一個與原字串順序相反的字串
print str[-3:-1] #擷取倒數第三位與倒數第一位之前的字元
print str[-3:] #擷取倒數第三位到結尾
print str[:-5:-3] #逆序擷取

元組、列表、字串互相轉換

s = "xxxxx"
print(list(s))
print(tuple(s))
l = ['a','b','c','d','e']
t = ('a','b','c','d','e')
print("".join(l))
print("".join(t))
#####結果如下
['x', 'x', 'x', 'x', 'x']
('x', 'x', 'x', 'x', 'x')
abcde
abcde

一些常用函式

1.strip() 從一個字串中刪除開頭或結尾處的字元序列

str=" hello world "
str.strip() #hello world

對於開頭和結尾:

  • s.lstrip(rm) : 刪除s字串中開頭處,位於 rm刪除序列的字元
str.lstrip('h')
#ello world
  • s.rstrip(rm) 刪除s字串中結尾處,位於 rm刪除序列的字元
str.rstrip('d')
#hello worl
  • 想刪除中間的空格,可以使用replace()函式
str1 = str.replace(' ','')
#helloworld

2.split()把一個字串分割成字串陣列

str.split(' ')
#['hello', 'world']

注意:上面兩種函式並不改變str的值,所以需要儲存函式值。