Python基礎篇--字符串string[索引、切片、方法...]

目錄

字符串索引---string[index]

字符串切片---string[start:end:step]

利用切片做字符串的翻轉

字符串的內置方法


python中字符串被定義爲引號之間的字符集合。
python支持使用成對的單引號或雙引號,三引號(三個連續的單引號或者雙引號)可以來包含特殊字符。
例如:'python'     "python"    '''python'''    """python"""  都是表示的python這個字符串

字符串是一種不可變的數據類型,何爲不可變:

a = 'name'
a[0] = 'N'        # 此時解釋器會報錯,因爲不可變的數據類型不可以在原地改變

不可變的也可稱作可哈希類型,作爲一串數字存放在內存中,而這串數字是唯一的。

字符串索引---string[index]

  python中字符串的索引值是從0開始的,也就是說字符串的第一個索引值爲0,也可以從後向前,從-1開始,-1 -2 -3...,超出最    大索引值會報錯.

a = 'hello, python'
a[0]
'h'
a[-1]
'n'
a[20]
# 報錯,超出了最大的索引值

字符串切片---string[start:end:step]

  切片的定義是:切片提取相應部分的數據,上邊界(end)不包括在提取字符串裏,步長(step)默認爲1,end值超過字符串索引值最大值不會報錯,會默認截取到結尾的字符

str1 = 'learning python is a blessing'
str1[0:6]    # 不包括6
'learn'
str1[0:]     # 從第0個字符到最後,包括最後的字符
'learning python is a blessing'
str1[:5]     # 從開頭的字符到第5個字符,不包括第5個字符
'lear'
str1[:-1]    # 從-29到第-1字符,不包括-1
'learning python is a blessin'
str1[:]      # 從開始到結尾所有的字符
'learning python is a blessing'
str1[-5:-1]  # 從-5 到 -1 字符 不包括-1
'ssin'
str1[3:1]    # 獲取的是空字符,不會報錯
''
str1[-1:-5]  # 獲取的是空字符,不會報錯
''
str1[1:10:2]   # 從第2個字符到第10個字符,每隔2個字符取一個
'erigp'

  利用切片做字符串的翻轉

str2 = 'python'
str2[::-1]
'nohtyp'

字符串的連接在上一篇已經講過,不清楚的朋友翻閱上一篇

字符串的內置方法


  .count(substr)----統計substr(子字符串)在字符串中出現的次數,也可以指定範圍統計

str3 = 'abcdaabc'
str3.count('a')
3

  .index(str)----返回str在字符串中的第一次出現的索引,如果str是個數大於一的字符串,返回str中的第一個字符的索引值

str3_1 = 'hey bro,come on.'
str3_1.index('o')      # 返回從左往右第一o的索引值
6
str3_1.index('bro')    # 返回b在字符串中的索引值
4
str3_1.index('p')      # 不存在的會報錯
...ValueError: substring not found    # 報錯信息在這裏簡寫了,沒有把全部的寫上


  .split('str', number)----以str分隔字符串,分隔number次,如果不指定number,默認分隔全部,返回值用一個列表包裹

str4 = 'hello,world,i am coming'
str4.split(',')
['hello', 'world', 'i am coming']

  .strip()----移除字符串開頭、結尾處的空白字符(包括空格,換行符\n,製表符\t)

str5 = '   hello   '
str5.strip()
'hello'

  'char'.join(str)----以char連接str中的每一個字符

str6 = 'snow'
'@'.join(str6)
's@n@o@w'

  .isalnuw(),.isdigit(),isalpha()----如果字符串至少有一個字符並且所有都是[字母或數字] [字母] [數組] ,則返回True,
  否則返回False

str7 = 'skier11'
str7.isalnum()
True
str8 = '8520'
str8.isdigit()
True
str9 = 'go snow'
str9.isalpha()
True

  .replace(old, new, [max])----將字符串中的old字符替換爲new字符,最多替換max次,默認全部替換

str10 = 'you are so beautiful, so you can be my gl.'
str10.replace('you', 'nancy')
'nancy are so beautiful, so nancy can be my gl.'

  關於字符大小寫的方法:

str11 = 'Python is mY love'
str11.lower()    # 大寫轉小寫
'python is my love'
str11.upper()    # 小寫轉大寫
'PYTHON IS MY LOVE'
str11.swapcase()    # 大小寫相互轉換
'pYTHON IS My LOVE'
str11.islower()    # 如果都是小寫,返回True,否則返回False
False
str11.isupper()    # 如果都是大寫,返回True,否則返回False
False
str11.capitalize()    # 第一個字母大寫
'Python is my love'
str11.title()    # 單詞首字母大寫
'Python Is My Love'

  關於字符串的方法還有很多,我只是列舉了一些常用的方法...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章