python基礎知識-字符串

引號區別

字符串可以用單引號,雙引號,三引號括起來,一般情況沒有任何區別

a='111'
b="111"
c='''111'''
print(a)
print(b)
print(c)

如果字符串中有引號,可以使用引號的嵌套或者使用轉義字符

# 引號嵌套
string="i'm good boy"
print(string)
string='this is "word"'
print(string)

# 轉義字符
string='i\'m good boy'
print(string)

三引號可以對應換行字符,單引號與雙引號不行

a='ab' \
  'cd'
b='''ab
cd'''
print(a)
print(b)

# 運行結果:
# abcd
# ab
# cd

切片

基本格式:
序列[start:end;step]
start:計數從start開始,默認爲0,可以爲負
end:計數以end結束,但不包括end,默認爲末尾,可以爲負
step:步長(變動幅度),默認爲1,可以爲負數

a='abcdefghijklmn'
print(a[::])
print(a[1:7:2])
print(a[-1:-4:-1])
print(a[-1:-4:1]) #取不到數據
print(a[::-1]) # 倒敘輸出

# 輸出結果
# abcdefghijklmn
# bdf
# nml
#
# nmlkjihgfedcba

start與end正負必須一致,end-start>0,步長必須爲正,反之步長爲負

常用操作方法

查找

find

基本用法:字符串序列.find(需要查找子串,開始位置下標,結束位置下標)
開始和結束位置下標可以省略,表示在整個字符串序列中查找,存在返回下標,不在返回-1

word='abcdefghijklmnopq'
print(word.find('bcd'))
print(word.find('bcd',4))
print(word.find('bcd',1,4))
# print(word.find('bcd',,4)) 不能這樣
# 運行結果:
# 1
# -1
# 1

rfind表示從右開始查找

index

與find幾乎一樣,但區別爲:若需要查找子串存在返回下標,不存在則會報錯,有rindex

count

語法格式同find,返回查找到的子串個數,不存在則返回0

word='abcdefghbcdlmnopq'
print(word.count('bcd'))
print(word.count('bcd',10,15))
# 運行結果:
# 2
# 0

修改

replace

基本用法:字符串序列.replace(舊子串,新子串,替換次數)
替換次數可以不寫,默認全部替換

word='abcdssddasabcdsadasdsadabcsadabc'
word_new=word.replace('abc','') # 把abc替換成空格
print(word)
print(word_new)

word_new=word.replace('abc','',1)
print(word_new)
# 運行結果:
# abcdssddasabcdsadasdsadabcsadabc
# dssddasdsadasdsadsad
# dssddasabcdsadasdsadabcsadabc

返回修改後的字符串,不會修改願有字符串,字符串是不可變數據類型

split

作用:進行分割,返回一個列表,丟失分割符變爲空
基本用法:字符串序列.split(分割字符,分割字符出現次數)

# 特例:分割符出現在首尾,則會出現空串
word='abcdssddasabcdsadasdsadabcsadabc'
word_new=word.split('abc')
print(word_new)
print(word)
#輸出結果:
# ['', 'dssddas', 'dsadasdsad', 'sad', '']
# abcdssddasabcdsadasdsadabcsadabc

# 特例:分割符連續出現,也會出現空串
word='saddasdascccxvcv'
word_new=word.split('das')
print(word_new)
# 輸出結果:
# ['sad', '', 'cccxvcv']

# 常例:
word='dadsahjksdsdhjkdssdds'
word_new=word.split('jk')
print(word_new)
word_new=word.split('jk',1)
print(word_new)
# 運行結果:
# ['dadsah', 'sdsdh', 'dssdds']
# ['dadsah', 'sdsdhjkdssdds']

最後list元素爲num+1

join

作用:split方法的逆方法,將列表(或元組)中多個字符串採用固定的分隔符連接在一起
基本用法:字符或子串.join(要合併的列表或元組)

list=['adss','asddsa','dsasadasd']
str='-'
new_str=str.join(list)
print(new_str)

# 運行結果:
# adss-asddsa-dsasadasd

其它函數

  • title:將字符串每個單詞首字母轉成大寫,會改變原有字符
  • lower:將字符串中大寫轉小寫
  • upper:將字符串中小寫轉大寫

判斷

startswith和endswith

作用:判斷字符串中是否以指定字符開頭或結尾,是則返回True,否則返回False
基本用法:字符串序列.startswith(子串,開始位置下標,結束位置下標)

word='fdssdfdsfdsdf'
print(word.startswith('fds'))
print(word.startswith('fds',1))
print(word.endswith('sdf',1))

# 運行結果:
# True
# False
# True

其它函數

  • isalpha:存在字符且所有字符爲字母
  • isdigit:存在字符且所有字符爲數字
  • isalnum:是否全爲數字或字母或數字字母組合
  • isspace:是否全爲空白

空格既不是字母也不是數字

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