python如何正確的操作字符串
0x01 字符串(string)
字符串是 Python 中最常用的數(shù)據(jù)類型,同時支持單引號和雙引號。使用雙引號時打印字符串時用單引號。
>>> "Hello world!" 'Hello world!' >>> 'Hello world!' 'Hello world!' >>> "Let's go!" "Let's go!" >>> 'she said "Hello world!" ' 'she said "Hello, world!" '
引號轉(zhuǎn)義
上述示例可使用反斜杠(\)對引號進(jìn)行轉(zhuǎn)義。
>>> 'Let\'s go!' "Let's go!" >>> "\"Hello, world!\" she said" '"Hello, world!" she said'
拼接字符串
通常使用 +號拼接字符串,像數(shù)字相加一樣。
>>> "she said " + '"Hello world!"' 'she said "Hello world!"' >>> a = "she said " >>> b = '"Hello world!"' >>> a + b 'she said "Hello world!"'
依次輸入兩個字符串時,也可實(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
長字符串
可使用三引號表示很長的字符串(跨越多行的字符串)。
>>> """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 + 5 12 >>> print("Hello \ world!") Hello world! >>> print \ ('Hello world') Hello world
索引( indexing)
對于字符串字面量,可直接對其執(zhí)行索引操作,無需先將其賦給變量。
>>> 'Hello'[1] 'e'
如果函數(shù)調(diào)用返回一個序列,可直接對其執(zhí)行索引操作。
>>> yearnum = input('please input year: ')[3] please input year: 2021 >>> yearnum '1'
將序列與數(shù)字n相乘時,將重復(fù)這個序列n次來創(chuàng)建一個新序列。
>>> '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)換成一個字符列表。
>>> 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)換說明符,指出了要將值插入什么地方 并在右邊指定要設(shè)置其格式的值。指定要設(shè)置其格式的值時,可使用單個值(如字符串或數(shù)字),可使用元組(如果要設(shè)置多個值的格式),還可使用字典,其中最常見的是元組。
>>> format = "Hello, %s. %s !" >>> values = ('world', 'python') >>> format % values 'Hello, world. python !'
模板字符串
包含等號的參數(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.''
如果變量與替換字段同名,還可使用一種簡寫。在這種情況下,使用f字符串——在字符串前面加上f。(Python 3.6+)
>>> from math import e >>> f"Euler's constant is roughly {e}." # 等價于 "Euler's constant is roughly {e}.".format(e=e) "Euler's constant is roughly 2.718281828459045."
0x03 如何設(shè)置格式
字符串包含有關(guān)如何設(shè)置格式的信息, 而這些信息是使用一種微型格式指定語言 (mini-language)指定的。每個值都被插入字符串中,以替換用花括號括起的替換字段。 替換字段由如下部分組成,其中每個部分 都是可選的。
- 字段名:索引或標(biāo)識符,指出要設(shè)置哪個值的格式并使用結(jié)果來替換該字段。除指定值 外,還可指定值的特定部分,如列表的元素。
- 轉(zhuǎn)換標(biāo)志:跟在嘆號后面的單個字符。當(dāng)前支持的字符包括r(表示repr)、s(表示str) 和a(表示ascii)。如果你指定了轉(zhuǎn)換標(biāo)志,將不使用對象本身的格式設(shè)置機(jī)制,而是使 用指定的函數(shù)將對象轉(zhuǎn)換為字符串,再做進(jìn)一步的格式設(shè)置。
- 格式說明符:跟在冒號后面的表達(dá)式(這種表達(dá)式是使用微型格式指定語言表示的)。格 式說明符讓我們能夠詳細(xì)地指定最終的格式,包括格式類型(如字符串、浮點(diǎn)數(shù)或十六 進(jìn)制數(shù)),字段寬度和數(shù)的精度,如何顯示符號和千位分隔符,以及各種對齊和填充方式。
字段名
只需向format提供要設(shè)置其格式的未命名參數(shù),并在格式字符串中使用 未命名字段。此時,將按順序?qū)⒆侄魏蛥?shù)配對。你還可給參數(shù)指定名稱,這種參數(shù)將被用于相 應(yīng)的替換字段中。你可混合使用這兩種方法。
>>> "{foo} {} {bar} {}".format(1, 2, bar=4, foo=3) '3 1 4 2'
還可通過索引來指定要在哪個字段中使用相應(yīng)的未命名參數(shù),這樣可不按順序使用未命名 參數(shù)。
>>> "{foo} {1} {bar} {0}".format(1, 2, bar=4, foo=3) '3 2 4 1'
并非只能使用提供的值本身,而是可訪問其組成部分,可使用索引,還可使用句點(diǎ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表 示(這里是一個字符串字面量)。函數(shù)ascii創(chuàng)建只包含ASCII字符的表示。
>>> print("{pi!s} {pi!r} {pi!a}".format(pi="π")) π 'π' '\u03c0'
格式說明
(即冒號后面)使用字符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中幾個很有用的常量
- string.digits:包含數(shù)字0~9的字符串。
- string.ascii_letters:包含所有ASCII字母(大寫和小寫)的字符串。
- string.ascii_lowercase:包含所有小寫ASCII字母的字符串。
- string.printable:包含所有可打印的ASCII字符的字符串。
- string.punctuation:包含所有ASCII標(biāo)點(diǎn)字符的字符串。
- string.ascii_uppercase:包含所有大寫ASCII字母的字符串。
填充方法
字符串填充字符方法
center、 ljust、 rjust、 zfill
split
如果沒有指定分隔符,將默認(rèn)在單個或多個連續(xù)的空白字符(空格、制表符、換行符 等)處進(jìn)行拆分
>>> seq = ['1', '2', '3', '4', '5'] >>> sep = '+' >>> sep.join('+') # 合并一個字符串列表 '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 操作字符串的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python連接kafka加載數(shù)據(jù)的項目實(shí)踐
本文主要介紹了python連接kafka加載數(shù)據(jù)的項目實(shí)踐,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-05-05python實(shí)現(xiàn)ModBusTCP協(xié)議的client功能
Modbus TCP 是一種基于 TCP/IP 協(xié)議棧的 Modbus 通信協(xié)議,它用于在工業(yè)自動化系統(tǒng)中進(jìn)行設(shè)備之間的通信,只要通過pymodbus或pyModbusTCP任意模塊就可以實(shí)現(xiàn),本文采用pymodbus,感興趣的朋友跟隨小編一起看看吧2023-10-10如何使用Python進(jìn)行數(shù)據(jù)分析之方差分析詳解
這篇文章主要給大家介紹了關(guān)于如何使用Python進(jìn)行數(shù)據(jù)分析之方差分析的相關(guān)資料,方差分析是一種常用的對數(shù)據(jù)進(jìn)行分析的方法,用于兩個及兩個以上樣本均數(shù)和方差差別的顯著性檢驗,需要的朋友可以參考下2024-03-03Python filter()及reduce()函數(shù)使用方法解析
這篇文章主要介紹了Python filter()及reduce()函數(shù)使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09Python利用pandas和matplotlib實(shí)現(xiàn)繪制堆疊柱狀圖
在數(shù)據(jù)可視化中,堆疊柱狀圖是一種常用的圖表類型,它能夠清晰地展示多個類別的數(shù)據(jù),本文將演示如何使用 Python 的 pandas 和 matplotlib 庫繪制優(yōu)化的堆疊柱狀圖,需要的可以參考下2023-11-11tensorflow 獲取模型所有參數(shù)總和數(shù)量的方法
今天小編就為大家分享一篇tensorflow 獲取模型所有參數(shù)總和數(shù)量的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06numpy ndarray 按條件篩選數(shù)組,關(guān)聯(lián)篩選的例子
今天小編就為大家分享一篇numpy ndarray 按條件篩選數(shù)組,關(guān)聯(lián)篩選的例子,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11