python入門——字符串對象及切片

字符串

字符串的定義

字符串是 Python 中最常用的數據類型。字符串的定義有4種:

>>> a = 'Hello world!'
>>> b = "Hello world!"
>>> c = '''Hello world!'''
>>> d = """Hello world!"""

python中字符串的常見方法

  • capitalize 首字母大寫
>>> a
'hello world'
>>> a.capitalize()
'Hello world'
  • center 將字符串居中,第二個參數表示填充的符號
>>> a.center(15," ")
'  hello world  '
>>> a.center(50," ")
'                   hello world                    '
  • count 統計字符串中出現字符或者字符串次數
>>> a
'hello world'
>>> a.count("l")
3
>>> a.count("ll")
1
  • encode 按照編碼格式編碼字符串
>>> a = "haha"
>>> a.encode("utf-8")		將字符串轉化爲字節
b'haha'
  • endswith 判斷字符是否以xx結尾
>>> a.endswith("d")
True
>>> a.endswith("h")
False
  • startswith 判斷字符串是否以xxx開頭
>>> a.startswith("h")
True
>>> a.startswith("d")
False
  • find 查找字符串中某個字符或者字符串第一次出現的位置,如果不存在,則返回-1
  • rfind 查找字符或者字符串最後一個出現的位置,如果不存在,則返回-1
>>> a.find("d")
10
>>> a.find("s")
-1
>>> a.rfind("s")
-1
>>> a.rfind("l")
9
  • index 查找字符串中某個字符或者字符串第一次出現的位置,如果不存在,則拋出異常
  • rindex 查找字符或者字符串最後一個出現的位置,如果不存在,則拋出異常
>>> a.index("d")
10
>>> a.index("s")
ValueError: substring not found
>>> a.rindex("s")
ValueError: substring not found
>>> a.rindex("l")
9
  • format 格式化字符串
>>> "{}{}".format("你","好")
'你好'
>>> "{0}{1}{2}{1}".format("你","好","不")
'你好不好'
  • join 用來拼接字符串,參數是一個可迭代對象
>>> a = "__"
>>> str =("haha","xixi","hehe")
>>> a.join(str)
'haha__xixi__hehe'
  • split 分割字符串,默認分割次數位-1,即分割所有,可修改
>>> a = "你 是 一 個 好 人"
>>> a.split(" ")
['你', '是', '一', '個', '好', '人']
>>> a.split(" ",1)		只分割一次
['你', '是 一 個 好 人']
  • lower 轉小寫
  • upper 轉大寫
>>> a ="dsanjloinDASUIHI"
>>> a.upper()
'DSANJLOINDASUIHI'
>>> a.lower()
'dsanjloindasuihi'
  • title 轉換字符串爲一個符合標題的規則
>>> a = "this is a big world"
>>> a.title()
'This Is A Big World'
  • strip 清除字符串兩邊的空格
  • rstrip 清除右邊的空格
  • lstrip 清除左邊的空格
>>> a = "        haha         "
>>> a.strip()
'haha'
>>> a.rstrip()
'        haha'
>>> a.lstrip()
'haha         '
  • replace 替換字符串
>>> a = "我是一個好人"
>>> a.replace("我","你")
'你是一個好人'

字符串的判斷方法

 str.istitle					判斷字符串是不是標題
 str.isspace					判斷是不是空白字符
 str.islower			 		判斷是不是小寫字母
 str.isupper			 		判斷是不是大字母
 str.isalnum			 		判斷是不是有字母和數字組成
 str.isalpha			 		判斷是不是有字母組成
 str.isdigit			 		判斷是不是數字組成

切片

切片是Python提供用來切割、分割、截取容器的方式,切片是一個前閉後開的區間。

>>> ls=[1,2,3,4,5,6,7,8,9]
  • 容器[start:] 從start位置開始截取容器,截取到末尾
>>> ls[3:]
[4, 5, 6, 7, 8, 9]
  • 容器[start:end] 從start位置開始,到end位置結束,不包含end位(左閉右開)
>>> ls[3:7]
[4, 5, 6, 7]
  • 容器[:end] 如果:左側不寫,默認(0)就下標爲0的位置開始
>>> ls[:7]
[1, 2, 3, 4, 5, 6, 7]
  • 容器[start: end:step] step表示步長,默認是1,可以自己指定
>>> ls[2:7:2]
[3, 5, 7]
  • 容器[::-1] 翻轉容器
>>> ls[::-1]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
  • 容器[start:] 若start大於len.容器,不會報錯,返回空
>>> ls[20:]
[]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章