字串就是一串字符, 表示文本型別的資料, 可以用"一對雙引號"或者'一對單引號'定義一個字串, 字串定義格式為
字串變數名 = '字串的文本內容'
常用函式/操作

獲取字串中的指定位置字符( 根據索引)
text = 'abcde'
print(text[1])

len(), 獲取字串的長度
text = 'hello'
print('字串的長度是:% d' % len(text))

count(), 獲取指定字符或字串在字串中出現的次數
text = 'abc abc'
print('字串ab在字串中出現的次數是:%d' % text.count('ab'))

index(), 獲取指定字符或字串在字串中首次出現的位置
text = 'abc abc'
print('字串ab在字串中首次出現的位置是:%d' % text.index('ab'))

判斷型別
isspace(), 判斷字串是否是空白字串( 是則回傳True, 不是則回傳False)
text = ' '
print('一個空格是否為空白字符:%s' % text.isspace())
text = ' '
print('多個空格是否為空白字符:%s' % text.isspace())
text = ' a'
print('包含空格和字母是否為空白字符:%s' % text.isspace())

isdecimal(), 判斷字串是否是純數字( 是則回傳True, 不是則回傳False)
text = '123'
print('字串123 是否是純數字:%s' % text.isdecimal())
text = '123a'
print('字串123a 是否是純數字:%s' % text.isdecimal())

startwith(), 判斷字串是否以指定字串開頭( 是則回傳True, 不是則回傳False)
text = 'hello python'
print('字串hello python 是否以he開頭: %s' % text.startswith('he'))

endswith(), 判斷字串是否已指定字串結尾( 是則回傳True, 不是則回傳False)
text = 'hello python'
print('字串hello python 是否以on結尾: %s' % text.endswith('on'))

find(), 查找指定字串在字串中出現的位置( 有則回傳字串所在的索引位置, 沒有則回傳-1)
text = 'hello python'
print('在字串hello python 查找字串e 出現的位置: %s' % text.find('e'))
print('在字串hello python 查找字串a 出現的位置: %s' % text.find('a'))

replace(), 替換字串( 第一個引數寫需要被替換的字串, 第二個引數寫替換后的字串)
text = 'hello python'
print(text.replace('he', 'aa'))

strip(), 去除字串來兩邊的空白字符
text = ' hello python '
print('去除空格前:%s' % text)
print('去除空格后:%s' % text.strip())

split(), 將字串按照指定分隔符, 轉換成串列
text = '張三,李四,王五,趙六'
names = text.split(',')
print(names)

join(), 按照指定分隔符, 將串列轉換成字串
names = ['張三', '李四', '王五', '趙六']
print(','.join(names))

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/296820.html
標籤:其他
上一篇:DC-1靶機的滲透學習
