python如何正確的操作字符串
字符串是 Python 中最常用的數(shù)據(jù)類型,同時(shí)支持單引號(hào)和雙引號(hào)。使用雙引號(hào)時(shí)打印字符串時(shí)用單引號(hào)。
>>> 'Hello world!'’Hello world!’>>> ’Hello world!’’Hello world!’>>> 'Let’s go!''Let’s go!'>>> ’she said 'Hello world!' ’’she said 'Hello, world!' ’引號(hào)轉(zhuǎn)義
上述示例可使用反斜杠()對(duì)引號(hào)進(jìn)行轉(zhuǎn)義。
>>> ’Let’s go!’'Let’s go!'>>> ''Hello, world!' she said'’'Hello, world!' she said’拼接字符串
通常使用 +號(hào)拼接字符串,像數(shù)字相加一樣。
>>> 'she said ' + ’'Hello world!'’’she said 'Hello world!'’>>> a = 'she said '>>> b = ’'Hello world!'’>>> a + b’she said 'Hello world!'’
依次輸入兩個(gè)字符串時(shí),也可實(shí)現(xiàn)字符串拼接。
>>> 'she said ' ’'Hello world!'’ ’she said 'Hello world!'’# 只有輸入的是字符串才有用>>> a = 'she said '>>> b = ’'Hello world!'’>>> a b File '<stdin>', line 1 a b ^SyntaxError: invalid syntax長(zhǎng)字符串
可使用三引號(hào)表示很長(zhǎng)的字符串(跨越多行的字符串)。
>>> '''like this'''’like this’>>> print(’’’long long ago!'Hello world!'she said.’’’)long long ago!'Hello world!'she said.
常規(guī)字符串也可橫跨多行。只要在行尾加上反斜杠,反斜杠和換行符將被轉(zhuǎn)義,即被忽略。
>>> 1 + 2 + 4 + 512>>> print('Hello world!')Hello world!>>> print (’Hello world’)Hello world索引( indexing)
對(duì)于字符串字面量,可直接對(duì)其執(zhí)行索引操作,無(wú)需先將其賦給變量。
>>> ’Hello’[1]’e’
如果函數(shù)調(diào)用返回一個(gè)序列,可直接對(duì)其執(zhí)行索引操作。
>>> yearnum = input(’please input year: ’)[3]please input year: 2021>>> yearnum’1’
將序列與數(shù)字n相乘時(shí),將重復(fù)這個(gè)序列n次來(lái)創(chuàng)建一個(gè)新序列。
>>> ’python’ * 3 ’pythonpythonpython’運(yùn)算符in
要檢查特定的值是否包含在序列中,可使用運(yùn)算符in
>>> access_mode = ’rw+’>>> ’w’ in access_mode True>>> ’x’ in access_mode False>>> subject = ’$$$ Get rich now!!! $$$’>>> ’$$$’ in subject True創(chuàng)建列表
使用函數(shù)list ,可以快速將字符串轉(zhuǎn)換成一個(gè)字符列表。
>>> somelist = list(’Hello’)>>> somelist[’H’, ’e’, ’l’, ’l’, ’o’]
將字符列表轉(zhuǎn)換為字符串。
>>>’’.join(somelist)切片賦值
>>> name = list(’Perl’)>>> name [’P’, ’e’, ’r’, ’l’]>>> name[2:] = list(’ar’)>>> name [’P’, ’e’, ’a’, ’r’]>>> name = list(’Perl’)>>> name[1:] = list(’ython’)>>> name [’P’, ’y’, ’t’, ’h’, ’o’, ’n’]0x02 字符串格式化
格式字符串中的%s稱為轉(zhuǎn)換說(shuō)明符,指出了要將值插入什么地方 并在右邊指定要設(shè)置其格式的值。指定要設(shè)置其格式的值時(shí),可使用單個(gè)值(如字符串或數(shù)字),可使用元組(如果要設(shè)置多個(gè)值的格式),還可使用字典,其中最常見(jiàn)的是元組。
>>> format = 'Hello, %s. %s !'>>> values = (’world’, ’python’)>>> format % values ’Hello, world. python !’模板字符串
包含等號(hào)的參數(shù)稱為關(guān)鍵字參數(shù),
>>> from string import Template>>> tmpl = Template('Hello, $param1! $param2 !')>>> tmpl.substitute(param1='world', param2='Python') ’Hello, world! Python !’字符串方法format
>>> '{}, {} and {}'.format('first', 'second', 'third') ’first, second and third’>>> '{0}, {1} and {2}'.format('first', 'second', 'third') ’first, second and third’>>> '{3} {0} {2} {1} {3} {0}'.format('be', 'not', 'or', 'to') ’to be or not to be’>>> from math import pi>>> '{name} 約等于 {value:.2f}.'.format(value=pi, name='π') ’π 約等于 3.14.’’
如果變量與替換字段同名,還可使用一種簡(jiǎn)寫(xiě)。在這種情況下,使用f字符串——在字符串前面加上f。(Python 3.6+)
>>> from math import e>>> f'Euler’s constant is roughly {e}.' # 等價(jià)于 'Euler’s constant is roughly {e}.'.format(e=e)'Euler’s constant is roughly 2.718281828459045.'0x03 如何設(shè)置格式
字符串包含有關(guān)如何設(shè)置格式的信息, 而這些信息是使用一種微型格式指定語(yǔ)言 (mini-language)指定的。每個(gè)值都被插入字符串中,以替換用花括號(hào)括起的替換字段。 替換字段由如下部分組成,其中每個(gè)部分 都是可選的。
字段名:索引或標(biāo)識(shí)符,指出要設(shè)置哪個(gè)值的格式并使用結(jié)果來(lái)替換該字段。除指定值 外,還可指定值的特定部分,如列表的元素。 轉(zhuǎn)換標(biāo)志:跟在嘆號(hào)后面的單個(gè)字符。當(dāng)前支持的字符包括r(表示repr)、s(表示str) 和a(表示ascii)。如果你指定了轉(zhuǎn)換標(biāo)志,將不使用對(duì)象本身的格式設(shè)置機(jī)制,而是使 用指定的函數(shù)將對(duì)象轉(zhuǎn)換為字符串,再做進(jìn)一步的格式設(shè)置。 格式說(shuō)明符:跟在冒號(hào)后面的表達(dá)式(這種表達(dá)式是使用微型格式指定語(yǔ)言表示的)。格 式說(shuō)明符讓我們能夠詳細(xì)地指定最終的格式,包括格式類型(如字符串、浮點(diǎn)數(shù)或十六 進(jìn)制數(shù)),字段寬度和數(shù)的精度,如何顯示符號(hào)和千位分隔符,以及各種對(duì)齊和填充方式。字段名只需向format提供要設(shè)置其格式的未命名參數(shù),并在格式字符串中使用 未命名字段。此時(shí),將按順序?qū)⒆侄魏蛥?shù)配對(duì)。你還可給參數(shù)指定名稱,這種參數(shù)將被用于相 應(yīng)的替換字段中。你可混合使用這兩種方法。
>>> '{foo} {} {bar} {}'.format(1, 2, bar=4, foo=3) ’3 1 4 2’
還可通過(guò)索引來(lái)指定要在哪個(gè)字段中使用相應(yīng)的未命名參數(shù),這樣可不按順序使用未命名 參數(shù)。
>>> '{foo} {1} {bar} {0}'.format(1, 2, bar=4, foo=3) ’3 2 4 1’
并非只能使用提供的值本身,而是可訪問(wèn)其組成部分,可使用索引,還可使用句點(diǎn)表示法來(lái)訪問(wèn)導(dǎo)入的模塊中的方法、屬性、變量和函 數(shù)
>>> fullname = ['Alfred', 'Smoketoomuch']>>> 'Mr {name[1]}'.format(name=fullname) ’Mr Smoketoomuch’>>> import math>>> tmpl = 'The {mod.__name__} module defines the value {mod.pi} for π'>>> tmpl.format(mod=math) ’The math module defines the value 3.141592653589793 for π’轉(zhuǎn)換標(biāo)志
(s、r和a)指定分別使用str、repr和ascii進(jìn)行轉(zhuǎn)換。函數(shù)str通常創(chuàng)建外觀 普通的字符串版本。函數(shù)repr嘗試創(chuàng)建給定值的Python表 示(這里是一個(gè)字符串字面量)。函數(shù)ascii創(chuàng)建只包含ASCII字符的表示。
>>> print('{pi!s} {pi!r} {pi!a}'.format(pi='π')) π ’π’ ’u03c0’格式說(shuō)明
(即冒號(hào)后面)使用字符f(表示定 點(diǎn)數(shù))。
>>> 'The number is {num}'.format(num=42) ’The number is 42’>>> 'The number is {num:f}'.format(num=42) ’The number is 42.000000’>>> 'The number is {num:b}'.format(num=42) ’The number is 101010’0x04 字符串方法常量
模塊string中幾個(gè)很有用的常量
string.digits:包含數(shù)字0~9的字符串。 string.ascii_letters:包含所有ASCII字母(大寫(xiě)和小寫(xiě))的字符串。 string.ascii_lowercase:包含所有小寫(xiě)ASCII字母的字符串。 string.printable:包含所有可打印的ASCII字符的字符串。 string.punctuation:包含所有ASCII標(biāo)點(diǎn)字符的字符串。 string.ascii_uppercase:包含所有大寫(xiě)ASCII字母的字符串。 填充方法字符串填充字符方法
center、 ljust、 rjust、 zfill
split如果沒(méi)有指定分隔符,將默認(rèn)在單個(gè)或多個(gè)連續(xù)的空白字符(空格、制表符、換行符 等)處進(jìn)行拆分
>>> seq = [’1’, ’2’, ’3’, ’4’, ’5’]>>> sep = ’+’>>> sep.join(’+’) # 合并一個(gè)字符串列表’1+2+3+4+5’>>> ’1+2+3+4+5’.split(’+’)[’1’, ’2’, ’3’, ’4’, ’5’]>>> ’Using the default’.split()[’Using’, ’the’, ’default’]
以上就是python如何正確的操作字符串的詳細(xì)內(nèi)容,更多關(guān)于python 操作字符串的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 在Android中使用WebSocket實(shí)現(xiàn)消息通信的方法詳解2. 淺談python出錯(cuò)時(shí)traceback的解讀3. ASP 信息提示函數(shù)并作返回或者轉(zhuǎn)向4. Python importlib動(dòng)態(tài)導(dǎo)入模塊實(shí)現(xiàn)代碼5. windows服務(wù)器使用IIS時(shí)thinkphp搜索中文無(wú)效問(wèn)題6. 利用promise及參數(shù)解構(gòu)封裝ajax請(qǐng)求的方法7. python matplotlib:plt.scatter() 大小和顏色參數(shù)詳解8. .NET中l(wèi)ambda表達(dá)式合并問(wèn)題及解決方法9. JSP數(shù)據(jù)交互實(shí)現(xiàn)過(guò)程解析10. Nginx+php配置文件及原理解析
