數(shù)據(jù)類型-字符串
字符串
是 python最常見的基本數(shù)據(jù)類型之一,常見的定義方式是一對(duì)單引號(hào)( '……')
或者一對(duì)雙引號(hào) ("……")
創(chuàng)建,多行字符串也可使用三單引號(hào)
或者三雙引號(hào)
定義嗤谚。
1. 特點(diǎn)
-
不可變類型
: 在元素定義之后不能對(duì)其進(jìn)行修改
,否則會(huì)報(bào)錯(cuò) -
可以進(jìn)行切片和索引操作
: 索引下標(biāo)從零
開始
示例
a = "hello world"
b = 'hello python'
print(type(a), type(b))
print(type(a), type(b))
打印輸出結(jié)果顯示<class 'str'> <class 'str'>
,可以看出a
變量和b
變量的類型都是str
字符串枷畏,type
內(nèi)置函數(shù)用來查看變量或者對(duì)象的類型。
2. 索引 和 切片
下標(biāo)
又叫索引
,用來記錄元素的位置虱饿,方便通過下標(biāo)快速找出對(duì)應(yīng)的的數(shù)據(jù)拥诡,字符串的下標(biāo)是從 0
開始,在使用過程中要注意索引越界問題
語法
序列[索引位置]
示例
print(a[0])
print(a[1])
如果索引值超過字符串的長(zhǎng)度郭厌,程序會(huì)拋出錯(cuò)誤
IndexError: string index out of range
切片
是指對(duì)操作的對(duì)象截取一部分
,切片索引越界不會(huì)報(bào)錯(cuò)
雕蔽,如果超過元素的最大索引折柠,就按最大索引返回
語法
序列[開始位置下標(biāo):結(jié)束位置下標(biāo):步長(zhǎng)]
name = "abcdefg"
print(name[2:5:1]) # cde
print(name[2:5]) # cde
print(name[:5]) # abcde
print(name[1:]) # bcdefg
print(name[:]) # abcdefg
print(name[::2]) # aceg
print(name[:-1]) # abcdef, 負(fù)1表示倒數(shù)第一個(gè)數(shù)據(jù)
print(name[-4:-1]) # def
print(name[::-1]) # gfedcba
- 切片滿足
含頭不含尾的規(guī)則
,正負(fù)數(shù)都是一樣步長(zhǎng)
為可選參數(shù)
批狐,如果不傳扇售,默認(rèn)為1
自增
3. 字符串格式
3.1 %號(hào)占位符
字符串具有一種特殊的內(nèi)置操作:使用 % (取模) 運(yùn)算符
。 這也被稱為字符串的 格式化 或 插值 運(yùn)算符嚣艇。
轉(zhuǎn)換符 | 描述 |
---|---|
d | 有符號(hào)十進(jìn)制整數(shù) |
i | 有符號(hào)十進(jìn)制整數(shù) |
o | 有符號(hào)八進(jìn)制數(shù) |
f | 浮點(diǎn)十進(jìn)制格式 |
r | 字符串(使用repr()轉(zhuǎn)換任何 Python 對(duì)象) |
s | 字符串(使用str()轉(zhuǎn)換任何 Python 對(duì)象) |
a | 字符串(使用ascii()轉(zhuǎn)換任何 Python 對(duì)象) |
% | 不轉(zhuǎn)換參數(shù)承冰,在結(jié)果中輸出一個(gè) '%' 字符 |
age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
stu_id2 = 1000
# 1. 今年我的年齡是x歲 -- 整數(shù) %d
print('今年我的年齡是%d歲' % age)
# 結(jié)果: 今年我的年齡是18歲
# 2. 我的名字是x -- 字符串 %s
print('我的名字是%s' % name)
# 結(jié)果:我的名字是TOM
# 3. 我的體重是x公斤 -- 浮點(diǎn)數(shù) %f
print('我的體重是%.3f公斤' % weight)
# 結(jié)果: 我的體重是75.500公斤
# 4. 我的學(xué)號(hào)是x -- %d
print('我的學(xué)號(hào)是%d' % stu_id)
# 結(jié)果: 我的學(xué)號(hào)是1
# 4.1 我的學(xué)號(hào)是001
print('我的學(xué)號(hào)是%03d' % stu_id)
print('我的學(xué)號(hào)是%03d' % stu_id2)
# 結(jié)果: 我的學(xué)號(hào)是001
# 結(jié)果: 我的學(xué)號(hào)是1000
# 5. 我的名字是x,今年x歲了
print('我的名字是%s食零,今年%d歲了' % (name, age))
# 結(jié)果: 我的名字是TOM困乒,今年18歲了
# 5.1 我的名字是x,明年x歲了
print('我的名字是%s贰谣,明年%d歲了' % (name, age + 1))
# 結(jié)果: 我的名字是TOM娜搂,明年19歲了
# 6. 我的名字是x,今年x歲了吱抚,體重x公斤百宇,學(xué)號(hào)是x
print('我的名字是%s,今年%d歲了秘豹,體重%.2f公斤携御,學(xué)號(hào)是%06d' % (name, age, weight, stu_id))
# 結(jié)果: 我的名字是TOM,今年18歲了既绕,體重75.50公斤啄刹,學(xué)號(hào)是000001
3.2 字符串的 format() 方法
age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
stu_id2 = 1000
print('我的名字是{},今年{}歲了凄贩,體重{}公斤鸵膏,學(xué)號(hào)是{}'.format(name, age, weight, stu_id))
print('我的名字是{name},今年{age}歲了怎炊,體重{weight}公斤谭企,學(xué)號(hào)是{stu_id}'.format(stu_id=stu_id, weight=weight, name=name, age=age))
花括號(hào)和其中的字符(稱為
格式字段
)將替換為傳遞給str.format()
方法的對(duì)象廓译。花括號(hào)中的數(shù)字可用來表示傳遞給str.format()
方法的對(duì)象的位置债查。
3.3 f {} 格式字符串
age = 18
name = 'TOM'
weight = 75.5
stu_id = 1
stu_id2 = 1000
print(f'我的名字是{name}非区,今年{age}歲了,體重{weight}公斤盹廷,學(xué)號(hào)是{stu_id}'))
f
格式字符串的方法可以說就是str.format()
方法的簡(jiǎn)寫形式
4 字符串常用方法
4.1 查找
對(duì)于字符串來說征绸,查找
一個(gè)元素的位置應(yīng)該經(jīng)常使用的,查找就是找出元素
在在字符串中出現(xiàn)的位置
或者出現(xiàn)的次數(shù)
-
find()
: 檢測(cè)某個(gè)子串是否包含在這個(gè)字符串中俄占,如果存在
在返回這個(gè)子串開始的位置下標(biāo)
管怠,不存在則返回-1
。
語法
字符串序列.find(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.find('and')) # 12
print(mystr.find('and', 15, 30)) # 23
print(mystr.find('ands')) # -1
開始位置下標(biāo)
缸榄,結(jié)束位置下標(biāo)
都是可以省略的渤弛,不傳遞參數(shù)默認(rèn)就是在整個(gè)字符串中查找
-
index()
: 檢測(cè)某個(gè)子串是否包含在這個(gè)字符串中,如果存在
返回這個(gè)子串開始的位置下標(biāo)
甚带,不存在則報(bào)異常
她肯。
語法
字符串序列.index(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.index('and')) # 12
print(mystr.index('and', 15, 30)) # 23
print(mystr.index('ands')) # 報(bào)錯(cuò) ValueError:
-
rfind()
: 和find()功能相同,但查找方向?yàn)?右側(cè) 開始鹰贵。 -
rindex()
:和index()功能相同晴氨,但查找方向?yàn)?右側(cè) 開始。 -
count()
:返回某個(gè)子串在字符串中出現(xiàn)的次數(shù)
語法
字符串序列.count(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.count('and')) # 3
print(mystr.count('ands')) # 0
print(mystr.count('and', 0, 20)) # 1
4.2 修改
字符串是不可變類型碉输,修改指的是通過函數(shù)的形式修改字符串中的數(shù)據(jù)
-
replace()
:替換
語法
字符串序列.replace(舊子串, 新子串, 替換次數(shù))
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.replace('and', 'he'))
# 結(jié)果:hello world he itcast he itheima he Python
print(mystr.replace('and', 'he', 10))
# 結(jié)果:hello world he itcast he itheima he Python
print(mystr)
# 結(jié)果:hello world and itcast and itheima and Python
替換次數(shù)
可以不傳籽前,默認(rèn)就是全部字符串中匹配上了就改變, 如果傳入替換次數(shù)敷钾,查出子串出現(xiàn)次數(shù)聚假,則替換次數(shù)為該子串出現(xiàn)次數(shù)
數(shù)據(jù)按照是否能直接修改分為
可變類型
和不可變類型
兩種。字符串類型的數(shù)據(jù)修改的時(shí)候不能改變?cè)凶址?/code>闰非,屬于不能直接修改數(shù)據(jù)的類型即是不可變類型膘格。
-
split()
:按照指定字符分割字符串。
語法
字符串序列.split(分割字符, num)
num
表示的是分割字符出現(xiàn)的次數(shù)财松,即將來返回?cái)?shù)據(jù)個(gè)數(shù)為num+1個(gè)
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.split('and'))
# 結(jié)果:['hello world ', ' itcast ', ' itheima ', ' Python']
print(mystr.split('and', 2))
# 結(jié)果:['hello world ', ' itcast ', ' itheima and Python']
print(mystr.split(' '))
# 結(jié)果:['hello', 'world', 'and', 'itcast', 'and', 'itheima', 'and', 'Python']
print(mystr.split(' ', 2))
# 結(jié)果:['hello', 'world', 'and itcast and itheima and Python']
如果分割字符是
原有字符串中的子串
瘪贱,分割后則丟失該子串
。
-
join()
:用一個(gè)字符或子串合并字符串辆毡,即是將多個(gè)字符串合并為一個(gè)新的字符串菜秦。
語法
字符或子串.join(多字符串組成的序列)
示例
list1 = ['I', 'love', 'you']
t1 = ('aa', 'b', 'cc', 'dd')
print('_'.join(list1))
# 結(jié)果:I_love_you
print('...'.join(t1))
# 結(jié)果:aa...b...cc...ddd
-
capitalize()
:將字符串第一個(gè)字符轉(zhuǎn)換成大寫。
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.capitalize())
# 結(jié)果:Hello world and itcast and itheima and python
capitalize()函數(shù)轉(zhuǎn)換后舶掖,
只字符串第一個(gè)字符大寫球昨,其他的字符全都小寫
。
-
title()
:將字符串每個(gè)單詞首字母轉(zhuǎn)換成大寫
眨攘。
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.title())
# 結(jié)果:Hello World And Itcast And Itheima And Python
-
lower()
:將字符串中大寫轉(zhuǎn)小寫
主慰。
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.lower())
# 結(jié)果:hello world and itcast and itheima and python
-
upper()
:將字符串中小寫轉(zhuǎn)大寫
嚣州。
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.upper())
# 結(jié)果:HELLO WORLD AND ITCAST AND ITHEIMA AND PYTHON
-
lstrip()
:刪除字符串左側(cè)空白字符。 -
rstrip()
:刪除字符串右側(cè)空白字符共螺。 -
strip()
:刪除字符串兩側(cè)空白字符该肴。
-
ljust()
:返回一個(gè)原字符串左對(duì)齊
,并使用指定字符(默認(rèn)空格)填充至對(duì)應(yīng)長(zhǎng)度 的新字符串
。
語法
字符串序列.ljust(長(zhǎng)度, 填充字符)
示例
mystr = 'hello'
mystr1 = mystr.ljust(10, '.')
print(mystr1)
# 結(jié)果:hello.....
-
rjust()
:返回一個(gè)原字符串右對(duì)齊,并使用指定字符(默認(rèn)空格)填充至對(duì)應(yīng)長(zhǎng)度 的新字符串藐不,語法和ljust()相同匀哄。 -
center()
:返回一個(gè)原字符串居中對(duì)齊,并使用指定字符(默認(rèn)空格)填充至對(duì)應(yīng)長(zhǎng)度 的新字符串,語法和ljust()相同雏蛮。
示例
mystr = 'hello'
mystr1 = mystr.center(10, '.')
print(mystr1)
# 結(jié)果: ..hello...
4.3 判斷
判斷
是指符合條件與否涎嚼,返回的結(jié)果是布爾類型即True
或者False
-
startswith()
:檢查字符串是否是以指定子串開頭
,是則返回 True挑秉,否則返回 False法梯。如果設(shè)置開始和結(jié)束位置下標(biāo),則在指定范圍內(nèi)檢查衷模。
語法
字符串序列.startswith(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
示例
mystr = "hello world and itcast and itheima and Python "
print(mystr.startswith('hello'))
# 結(jié)果:True
print(mystr.startswith('hello', 5, 20))
# 結(jié)果False
-
endswith()
::檢查字符串是否是以指定子串結(jié)尾
鹊汛,是則返回 True蒲赂,否則返回 False阱冶。如果設(shè)置開始和結(jié)束位置下標(biāo),則在指定范圍內(nèi)檢查滥嘴。
語法
字符串序列.endswith(子串, 開始位置下標(biāo), 結(jié)束位置下標(biāo))
示例
mystr = "hello world and itcast and itheima and Python"
print(mystr.endswith('Python'))
# 結(jié)果:True
print(mystr.endswith('python'))
# 結(jié)果:False
print(mystr.endswith('Python', 2, 20))
# 結(jié)果:False
-
isalpha()
:如果字符串至少有一個(gè)字符
并且所有字符都是字母
則返回True
, 否則返回False
木蹬。
示例
mystr1 = 'hello'
mystr2 = 'hello12345'
print(mystr1.isalpha())
# 結(jié)果:True
print(mystr2.isalpha())
# 結(jié)果:False
-
isdigit()
:如果字符串只包含數(shù)字
則返回True
否則返回False
。
示例
mystr1 = 'aaa12345'
mystr2 = '12345'
print(mystr1.isdigit())
# 結(jié)果: False
print(mystr2.isdigit())
# 結(jié)果:False
-
isalnum()
:如果字符串至少有一個(gè)字符
并且所有字符都是字母
或數(shù)字
則返 回True
,否則返回False
若皱。
示例
mystr1 = 'aaa12345'
mystr2 = '12345-'
print(mystr1.isalnum())
# 結(jié)果:True
print(mystr2.isalnum())
# 結(jié)果:False
-
isspace()
:如果字符串中只包含空白
镊叁,則返回True
,否則返回False
走触。
mystr1 = '1 2 3 4 5'
mystr2 = ' '
print(mystr1.isspace())
# 結(jié)果:False
print(mystr2.isspace())
# 結(jié)果:True