字符串
1.定義:
字符串是一個(gè)有序的,不可修改的,以引號(hào)(單引/雙引號(hào))包圍的序列
單引號(hào): ' '
雙引號(hào): “” “”
三單引號(hào):' ' ‘(多用于代碼注釋)
三雙引號(hào): “ “ “(多用于代碼注釋)
單引號(hào)和雙引號(hào)的區(qū)別?
都是為字符串的標(biāo)準(zhǔn)格式,只是為了區(qū)分英語(yǔ)中的一些語(yǔ)義
>>> print("I ' am 18")
I ' am 18
>>> print('I "am 18')
I "am 18
>>>
>>> print ('''
... 1
... 2
... 3
... ''')
1
2
3
>>> print("""
... 1
... 2
... 3
... """)
1
2
3
- 字符串拼接
>>> a = "jrljs"
>>> b = " is"
>>> c = " nice"
>>> d = a + b + c
>>> d
'jrljs is nice'
3.特殊字符
特殊字符就是在字符串當(dāng)中起到特殊含義的字符
”\“ 轉(zhuǎn)義符,將字符串當(dāng)中的具有特殊含義的字符的特殊含義取消掉后繼續(xù)執(zhí)行;
"\n" 換行;
”\t“ 水平制表符,等同于tab鍵
”\“ 反斜杠符
占位符
在字符串當(dāng)中以指定的格式符號(hào)進(jìn)行占位,然后將指定的數(shù)據(jù)傳入字符串
%s 字符串占位符
%d 數(shù)字占位符
%f 浮點(diǎn)占位符
%.2f 控制浮點(diǎn)型數(shù)字占位符
>>> print("My name is %s"%("jrljs"))
My name is jrljs
>>> print("My name is %s"%('jrljs'))
My name is jrljs
>>> print('My name is %s'%('jrljs'))
My name is jrljs
>>>
>>> print("I am %d years old"%(18))
I am 18 years old
>>>
>>> print("My height is %f m"%(1.70))
My height is 1.700000 m
>>>
>>> print("My height is %.2f m"%(1.70))
My height is 1.70 m
4.字符串的索引
字符串中的每一個(gè)個(gè)體都稱作字符也是該字符串的一個(gè)元素,每一個(gè)元素都對(duì)應(yīng)一個(gè)索引值(下標(biāo)),可以使用len()方法查看一個(gè)序列的長(zhǎng)度
比如字符串'jrljs',可以按照下圖理解其下標(biāo)概念,索引號(hào)從0開(kāi)始
| j | r | l | j | s |
|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 |
字符串截?。鹤址甗start:end]
截取原則:包頭不包尾且截取方向是從左到右
>>> name = "jrljs"
>>> print(name[1:4])
rlj
步長(zhǎng)截?。鹤址甗start:end:step] 按照step步長(zhǎng)進(jìn)行隔取;
截取原則:包頭不包尾
默認(rèn)步長(zhǎng):字符串[start:end:step] 這三個(gè)參數(shù)都有默認(rèn)值,start,默認(rèn)值為0;end,默認(rèn)值字符串結(jié)尾元素;step,默認(rèn)值為1
步長(zhǎng):默認(rèn)值為1,那么它的取值范圍應(yīng)該是1-1=0,即全部都取出來(lái);
步長(zhǎng)為2,即2-1=1,即隔一個(gè)元素取一個(gè);
依次類推...
若step>0,表示從左向右進(jìn)行切片,此時(shí)start必須小于end才有結(jié)果。
若step<0,還是表示從左到右,只不過(guò)要反過(guò)來(lái)切片,此時(shí)start必須大于end才有結(jié)果??梢苑謨刹嚼斫?,第一步先反取,即[::-1]; 第二步按照從左到右,根據(jù)步長(zhǎng)依次取值
string = "hello world"
>>> print(string[0:7])
hello w
>>> print(string[:7])
hello w
>>>
>>> print(string[2:])
llo world
>>> print(string[:])
hello world
>>> print(string[::])
hello world
>>> print(string[::1])
hello world
>>> print(string[::2])
hlowrd
>>>
>>> print(string[::1])
hello world
>>> print(string[::-1])
dlrow olleh
>>> print(string[9:1:-1])
lrow oll
>>> print(string[9:1:-2])
lo l
>>> print(string[1:9:-2])
>>>
- 字符串查找
| 參數(shù) | 描述 |
|---|---|
| count | 計(jì)數(shù)功能,返回自定義字符在字符串中的總個(gè)數(shù) |
| find | 查找,返回從左第一個(gè)指定字符的索引,找不到返回-1 |
| rfind | 查找,返回從右第一個(gè)指定字符的索引,找不到返回-1 |
| index | 查找,返回從左第一個(gè)指定字符的索引,找不到報(bào)錯(cuò) |
| rindex | 查找,返回從右第一個(gè)指定字符的索引,找不到報(bào)錯(cuò) |
>>> print(string)
hello world
>>> print(string.count("l"))
3
>>> print(string.find("l"))
2
>>> print(string.rfind("l"))
9
>>> print(string.find("L"))
-1
>>> print(string.rfind("L"))
-1
>>> print(string)
hello world
>>> print(string.index("o"))
4
>>> print(string.rindex("o"))
7
>>> print(string.index("O"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
>>> print(string.rindex("O"))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: substring not found
6.字符串分割與替換
| 參數(shù) | 描述 |
|---|---|
| partition | 把mystr以str進(jìn)行分割,分割成三部分,str前,str自身和str后 |
| rpartition | 類似于 partition()函數(shù),不過(guò)是從右邊開(kāi)始. |
| splitlines | 按照行分隔,返回一個(gè)包含各行作為元素的列表,按照換行符分割 |
| split | 判斷字符串的分隔符切片 |
| replace | 從左到右替換指定的元素,可以指定替換的個(gè)數(shù),默認(rèn)全部替換 |
>>> print(string)
hello world
>>> print(string.partition("o"))
('hell', 'o', ' world')
>>> print(string.rpartition("o"))
('hello w', 'o', 'rld')
>>>
>>>
>>> print(string)
hello world
>>> print(string.splitlines())
['hello world']
>>> print(string.split())
['hello', 'world']
>>> string2 = "hello\n world\n python\n"
>>> print(string2)
hello
world
python
>>> print(string2.splitlines())
['hello', ' world', ' python']
>>> print(string2.split())
['hello', 'world', 'python']
>>>
>>>
>>> print(string)
hello world
>>> print(string.replace('o','O'))
hellO wOrld
>>> print(string.replace('o','O',1))
hellO world
7.字符串修飾
| 參數(shù) | 描述 |
|---|---|
| center | 讓字符串在指定的長(zhǎng)度居中,如果不能居中左短右長(zhǎng),可以指定填充內(nèi)容,默認(rèn)以空格填充 |
| ljust | 讓字符串在指定的長(zhǎng)度左齊,可以指定填充內(nèi)容,默認(rèn)以空格填充 |
| rjust | 讓字符串在指定的長(zhǎng)度右齊,可以指定填充內(nèi)容,默認(rèn)以空格填充 |
| zfill | 將字符串填充到指定的長(zhǎng)度,不足地方用0從左開(kāi)始補(bǔ)充 |
| format | 按照順序,將后面的參數(shù)傳遞給前面的大括號(hào) |
| strip | 默認(rèn)去除兩邊的空格,去除內(nèi)容可以指定 |
| rstrip | 默認(rèn)去除右邊的空格,去除內(nèi)容可以指定 |
| lstrip | 默認(rèn)去除左邊的空格,去除內(nèi)容可以指定 |
>>> print(string)
hello world
>>> print(string.center(15))
hello world
>>> print(string.center(15,'*'))
**hello world**
>>>
>>>
>>> print(string.ljust(15))
hello world
>>> print(string.ljust(15,'*'))
hello world****
>>> print(string.rjust(15,'*'))
****hello world
>>>
>>>
>>> print(string)
hello world
>>> print(string.zfill(15))
0000hello world
>>>
>>>
>>> string = ' hello world '
>>> print(string)
hello world
>>> print(string.strip())
hello world
>>> print(string.lstrip())
hello world
>>> print(string.rstrip())
hello world
>>>
>>>
>>> string = "{0} is {1}"
>>> print(string.format("jrljs","nice"))
jrljs is nice
8.字符串變形
| 參數(shù) | 描述 |
|---|---|
| upper | 將字符串當(dāng)中所有的字母轉(zhuǎn)換為大寫 |
| lower | 將字符串當(dāng)中所有的字母轉(zhuǎn)換為小寫 |
| swapcase | 將字符串當(dāng)中所有的字母大小寫互換 |
| title | 將字串符當(dāng)中的單詞首字母大寫,單詞以非字母劃分 |
| capitalize | 只有字符串的首字母大寫 |
| expandtabs | 把字符串中的 tab 符號(hào)('\t')轉(zhuǎn)為空格,tab 符號(hào)('\t')默認(rèn)的空格數(shù)是 8,可以試下8,12 |
>>> print('hello'.upper())
HELLO
>>>
>>> print('HELLO'.lower())
hello
>>>
>>> print('HH##ZZ'.swapcase())
hh##zz
>>> print('*qwe*'.swapcase())
*QWE*
>>>
>>> print('I \t is \t 18'.expandtabs())
I is 18
>>> print('I \t is \t 18'.expandtabs(10))
I is 18
>>> print('I \t is \t 18'.expandtabs(4))
I is 18
- 字符串判斷
| 參數(shù) | 描述 |
|---|---|
| isalnum | 判斷字符串是否完全由字符或數(shù)字組成 |
| isalpha | 判斷字符串是否完全由字母組成 |
| isdigit | 判斷字符串是否完全由數(shù)字組成 |
| isupper | 判斷字符串當(dāng)中的字母是否完全是大寫 |
| islower | 判斷字符串當(dāng)中的字母是否完全是小寫 |
| istitle | 判斷字符串是否滿足title格式 |
| isspace | 判斷字符串是否完全由空格組成 |
| startswith | 判斷字符串的開(kāi)頭字符,也可以截取判斷 |
| endswith | 判斷字符串的結(jié)尾字符,也可以截取判斷 |
>>> print('123456'.isalnum())
True
>>> print('12345ab'.isalnum())
True
>>> print('abcde'.isalnum())
True
>>>
>>> print('abcdef'.isalpha())
True
>>> print('abcdef#'.isalpha())
False
>>> print('abcdef3#'.isalpha())
False
>>>
>>> print("123456".isdigit())
True
>>> print("#####".isdigit())
False
>>> print("abcdef".isdigit())
False
>>>
>>> print('HELLO'.isupper())
True
>>> print('HELLOaabbcc'.isupper())
False
>>> print('aabbcc'.isupper())
False
>>>
>>> print('Wo Ow'.istitle())
True
>>> print('wO oW'.istitle())
False
>>>
>>> print(' '.isspace())
True
>>> print(' Welcome '.isspace())
False
>>>
>>> print('Welcome'.startswith('W'))
True
>>> print('Welcome'.startswith('Wel'))
True
>>> print('Welcome'.endswith('e'))
True
>>> print('Welcome'.endswith('come'))
True
>>>
10.字符串編碼
encode 是編碼
decode 是解碼
>>> u = "陸"
>>> str1 = u.encode('gbk')
>>> print(str1)
b'\xc2\xbd'
>>> print(str2)
b'jrljs'
>>> str2 = u.encode('utf-8')
>>> print(str2)
b'\xe9\x99\x86'
>>>
>>> u1 = str1.decode('gbk')
>>> print(u1)
陸
>>> u2 = str2.decode('utf-8')
>>> print(u2)
陸
拓展
在python中解決編碼問(wèn)題
由于Python源代碼也是一個(gè)文本文件,所以,當(dāng)你的源代碼中包含中文的時(shí)候,在保存源代碼時(shí),就需要?jiǎng)?wù)必指定保存為UTF-8編碼。當(dāng)Python解釋器讀取源代碼時(shí),為了讓它按UTF-8編碼讀取,我們通常在文件開(kāi)頭寫上這兩行(python3默認(rèn)為utf-8 所以沒(méi)必要加文檔頭):
1、# -- coding: utf-8 --
2、#coding=utf-8
練習(xí)作業(yè):
BMI指數(shù)(Body Mass Index) 以稱身體質(zhì)量指數(shù)
BMI值計(jì)算公式: BMI = 體重(公斤) / 身高的平方(米)
例如:
一個(gè)人69公斤,身高是173公分
BMI = 69 / 1.73**2 = 23.05
標(biāo)準(zhǔn)表:
BMI < 18.5 體重過(guò)輕
18.5 <= BMI < 24 體重正常
BMI > 24 體重過(guò)重
要求: 輸入身高的體重,打印出BMI的值并打印體重狀況
解答:
weight = int(input("請(qǐng)輸入你的體重(kg):"))
hight = float(input("請(qǐng)輸入你的身高(m):"))
BMI = weight/pow(high,2)
if BMI < 18.5:
print(“體重過(guò)輕”)
elif BMI > 18.5:
print("體重過(guò)重")
else
print("體重剛剛好")