Python 基礎(chǔ)教程

Python 流程控制

Python 函數(shù)

Python 數(shù)據(jù)類型

Python 文件操作

Python 對象和類

Python 日期和時(shí)間

Python 高級知識

Python 參考手冊

Python 字符串(String)

在本教程中,您將學(xué)習(xí)如何用Python創(chuàng)建、格式化、修改和刪除字符串。此外,還將向您介紹各種字符串操作和函數(shù)。

Python中的字符串是什么?

字符串是字符序列。

字符只是一個(gè)符號。例如,英語具有26個(gè)字符。

計(jì)算機(jī)不處理字符,它們處理數(shù)字(二進(jìn)制)。即使您可能在屏幕上看到字符,在內(nèi)部它也被存儲和操縱為0和1的組合。

字符到數(shù)字的這種轉(zhuǎn)換稱為編碼,而相反的過程是解碼。ASCII和Unicode是一些常用的編碼。

在Python中,字符串是Unicode字符序列。引入U(xiǎn)nicode包括所有語言中的每個(gè)字符并帶來統(tǒng)一的編碼。您可以從此處了解有關(guān)Unicode的更多信息。

如何在Python中創(chuàng)建字符串?

可以通過將字符括在單引號或雙引號中來創(chuàng)建字符串。Python中甚至可以使用三引號,但通常用于表示多行字符串和文檔字符串。

# 下面這些都是等價(jià)的
my_string = 'Hello'
print(my_string)

my_string = "Hello"
print(my_string)

my_string = '''Hello'''
print(my_string)

# 三引號字符串可以擴(kuò)展多行
my_string = """Hello, welcome to
           the world of Python"""
print(my_string)

運(yùn)行該程序時(shí),輸出為:

Hello
Hello
Hello
Hello, welcome to
           the world of Python

如何訪問字符串中的字符?

我們可以使用索引訪問單個(gè)字符,并使用切片訪問一系列字符。索引從0開始。嘗試訪問超出索引范圍的字符將引發(fā)IndexError。索引必須是整數(shù)。我們不能使用float或其他類型,這將導(dǎo)致TypeError。

Python允許對其序列進(jìn)行負(fù)索引。

索引-1表示最后一項(xiàng),-2表示倒數(shù)第二項(xiàng),依此類推。我們可以使用切片運(yùn)算符(冒號)訪問字符串中的一系列項(xiàng)目。

str = '(cainiaoplus.com)'
print('str = ', str)

#第一個(gè)字符
print('str[0] = ', str[0])

#最后一個(gè)字符
print('str[-1] = ', str[-1])

#切片第二到第五個(gè)字符
print('str[1:5] = ', str[1:5])

#切片從第6個(gè)到倒數(shù)第2個(gè)字符
print('str[5:-2] = ', str[5:-2])

輸出結(jié)果:

str =  (cainiaoplus.com)
str[0] =  n
str[-1] =  m
str[1:5] =  hooo
str[5:-2] =  .c

如果嘗試訪問超出范圍的索引或使用十進(jìn)制數(shù),則會(huì)出現(xiàn)錯(cuò)誤。

# 索引必須在范圍內(nèi)
>>> my_string[15]  
...
IndexError: string index out of range

# 索引必須是整數(shù)
>>> my_string[1.5] 
...
TypeError: string indices must be integers

通過考慮索引位于元素之間,可以最好地可視化切片,如下所示。

如果要訪問范圍,則需要索引,該索引將從字符串中切出一部分。

Python中的元素切片

如何更改或刪除字符串?

字符串是不可變的。這意味著字符串的元素一旦分配就無法更改。我們可以簡單地將不同的字符串重新分配給相同的名稱。

>>> my_string = '(cainiaoplus.com)'
>>> my_string[5] = 'a'
...
TypeError: 'str' object does not support item assignment
>>> my_string = 'Python'
>>> my_string
'Python'

我們不能刪除或刪除字符串中的字符。但是使用del關(guān)鍵字可以完全刪除字符串。

>>> del my_string[1]
...
TypeError: 'str' object doesn't support item deletion
>>> del my_string
>>> my_string
...
NameError: name 'my_string' is not defined

Python字符串操作

字符串可以執(zhí)行許多操作,這使它成為Python中最常用的數(shù)據(jù)類型之一。

兩個(gè)或多個(gè)字符串的串聯(lián)

將兩個(gè)或多個(gè)字符串連接為單個(gè)字符串稱為串聯(lián)。

+ 運(yùn)算符在Python中執(zhí)行串聯(lián)操作。 簡單地將兩個(gè)字符串文字一起編寫,也可以將它們串聯(lián)在一起。

* 運(yùn)算符可以用來重復(fù)字符串的特定次數(shù)。

str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)

一起編寫兩個(gè)字符串文字也會(huì)像+運(yùn)算符一樣將它們串聯(lián)在一起。

如果要在不同的行中連接字符串,可以使用括號。

>>> # 兩個(gè)字符串文本在一起
>>> 'Hello ''World!'
'Hello World!'

>>> # 使用括號
>>> s = ('Hello '
...      'World')
>>> s
'Hello World'

遍歷字符串

使用for循環(huán),我們可以遍歷字符串。這是一個(gè)計(jì)算字符串中“ l”數(shù)的示例。

count = 0
for letter in 'Hello World':
    if(letter == 'l'):
        count += 1
print(count,'letters found')

字符串成員資格測試

我們可以使用in關(guān)鍵字來測試字符串中是否存在子字符串。

>>> 'a' in 'program'
True
>>> 'at' not in 'battle'
False

使用Python的內(nèi)置函數(shù)

可以使用sequence和string的各種內(nèi)置函數(shù)。

一些常用的是enumerate()和len()。enumerate()函數(shù)的作用是:返回一個(gè)枚舉對象。它以對的形式包含字符串中所有項(xiàng)的索引和值。這對于迭代很有用。

同樣,len()返回字符串的長度(字符數(shù))。

str = 'cold'

# enumerate()
list_enumerate = list(enumerate(str))
print('list(enumerate(str) = ', list_enumerate)

#字符數(shù)
print('len(str) = ', len(str))

Python字符串格式

轉(zhuǎn)義序列

如果我們想打印一個(gè)文本-他說:“What's there?”-我們不能使用單引號或雙引號。這將導(dǎo)致SyntaxError文本本身包含單引號和雙引號。

>>> print("He said, "What's there?"")
...
SyntaxError: invalid syntax
>>> print('He said, "What's there?"')
...
SyntaxError: invalid syntax

解決此問題的一種方法是使用三引號。另外,我們可以使用轉(zhuǎn)義序列。

轉(zhuǎn)義序列以反斜杠開頭,并且以不同的方式解釋。如果我們使用單引號表示字符串,則必須對字符串內(nèi)的所有單引號進(jìn)行轉(zhuǎn)義。雙引號也是如此。這是表示上述文本的方法。

# 使用三個(gè)單引號
print('''He said, "What's there?"''')

# 轉(zhuǎn)義單引號
print('He said, "What\'s there?"')

# 轉(zhuǎn)義雙引號
print("He said, \"What's there?\"")

這是Python支持的所有轉(zhuǎn)義序列的列表。

Python中的轉(zhuǎn)義序列
轉(zhuǎn)義序列描述
\newline反斜杠和換行符被忽略
\\反斜杠
\'單引號
\"雙引號
\aASCII鈴聲
\bASCII退格鍵
\fASCII換頁
\nASCII換行
\rASCII回車
\tASCII水平制表符
\vASCII垂直制表符
\ooo具有八進(jìn)制值的字符
\xHH具有十六進(jìn)制值HH的字符

這里有些示例

>>> print("C:\\Python32\\Lib")
C:\Python32\Lib

>>> print("This is printed\nin two lines")
This is printed
in two lines

>>> print("This is \x48\x45\x58 representation")
This is HEX representation

原始字符串忽略轉(zhuǎn)義序列

有時(shí)我們可能希望忽略字符串中的轉(zhuǎn)義序列。為此,我們可以將其放置在字符串的前面r或R前面。這意味著這是一個(gè)原始字符串,并且其中的任何轉(zhuǎn)義序列都將被忽略。

>>> print("This is \x61 \ngood example")
This is a
good example
>>> print(r"This is \x61 \ngood example")
This is \x61 \ngood example

用format()方法格式化字符串

與string對象一起使用的format()方法非常通用,并且在格式化字符串方面功能非常強(qiáng)大。格式字符串包含大括號{}作為占位符或被替換的替換字段。

我們可以使用位置參數(shù)或關(guān)鍵字參數(shù)來指定順序。

# 默認(rèn)(隱式)順序
default_order = "{}, {} and {}".format('John','Bill','Sean')
print('\n--- Default Order ---')
print(default_order)

# 使用位置參數(shù)排序
positional_order = "{1}, {0} and {2}".format('John','Bill','Sean')
print('\n--- Positional Order ---')
print(positional_order)

# 使用關(guān)鍵字參數(shù)的排序
keyword_order = "{s},  and {j}".format(j='John',b='Bill',s='Sean')
print('\n--- Keyword Order ---')
print(keyword_order)

format()方法可以具有可選的格式規(guī)范。它們使用冒號與字段名稱分開。例如,我們可以在給定的空間中左對齊<,右對齊>或^將字符串居中。我們還可以將整數(shù)格式化為二進(jìn)制,十六進(jìn)制等,并且浮點(diǎn)數(shù)可以四舍五入或以指數(shù)格式顯示。您可以使用大量的格式。請?jiān)L問此處以獲取該format()方法可用的所有字符串格式。

>>> # 格式化整數(shù)
>>> "Binary representation of {0} is {0:b}".format(12)
'Binary representation of 12 is 1100'

>>> # 格式化浮點(diǎn)數(shù)
>>> "Exponent representation: {0:e}".format(1566.345)
'Exponent representation: 1.566345e+03'

>>> # 四舍五入
>>> "One third is: {0:.3f}".format(1/3)
'One third is: 0.333'

>>> # 字符串對齊
>>> "|{:<10}|{:^10}|{:>10}|".format('butter','bread','ham')
'|butter    |  bread   |       ham|'

舊樣式格式

我們甚至可以像sprintf()在C編程語言中使用的舊樣式一樣格式化字符串。我們使用%運(yùn)算符來完成此任務(wù)。

>>> x = 12.3456789
>>> print('The value of x is %3.2f' %x)
The value of x is 12.35
>>> print('The value of x is %3.4f' %x)
The value of x is 12.3457

常見的Python字符串方法

字符串對象有許多可用的方法。上面提到的format()方法就是其中之一。常用的方法有l(wèi)ower()、upper()、join()、split()、find()、replace()等。這里是所有的完整列表中在Python中處理字符串的內(nèi)置方法

>>> "nhooo".lower()
'nhooo'
>>> "nhooo".upper()
'NHOOO'
>>> "This will split all words into a list".split()
['This', 'will', 'split', 'all', 'words', 'into', 'a', 'list']
>>> ' '.join(['This', 'will', 'join', 'all', 'words', 'into', 'a', 'string'])
'This will join all words into a string'
>>> 'Happy New Year'.find('ew')
7
>>> 'Happy New Year'.replace('Happy','Brilliant')
'Brilliant New Year'

                                                                                                                                                                                                   

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清