1. 程式人生 > >Python 3.7.1 基礎-資料型別-字串

Python 3.7.1 基礎-資料型別-字串

字串

1.基本內容

1.1 概念

字串就是一段文字(可能只有一個字母),由文字兩端的引號引起; Python中的文字資料由str物件或strings進行處理。
特點:字串是不可變(的Unicode碼點)序列

1.2 構造方法

(1)文字是字串字面值:

  • 單引號: ',允許文字中嵌入多對 雙引號"
  • 雙引號: ",允許 嵌入多對 單引號'
  • 三引號:'''""",允許嵌入多對單引號,雙引號。

(2)如果是一個物件,對物件使用str()方法

1.3 組成

stringliteral   ::=  [stringprefix](shortstring | longstring)
stringprefix    ::=  "r" | "u" | "R" | "U"
shortstring     ::=  "'" shortstringitem* "'" | '"' shortstringitem* '"'
longstring      ::=  "'''" longstringitem* "'''" | '"""' longstringitem* '"""'
shortstringitem ::=  shortstringchar | stringescapeseq
longstringitem  ::=  longstringchar | stringescapeseq
shortstringchar ::=  <any source character except "\" or newline or the quote>
longstringchar  ::=  <any source character except "\">
stringescapeseq ::=  "\" <any source character>

字串用字母’r’或’R’作為字首;這樣的字串稱為raw string並將反斜槓作為原義字元。因此,原始字串中的’\U’ 和’\u’ 轉義符是不會特殊對待。

1.3.1 轉義

(1)除非出現字首’r’ 或’R’,否則字串和位元組字面量中的轉義序列依照類似標準C使用的規則解釋。可識別的轉義序列有:

轉義序列 含義
\newline 忽略反斜槓和換行
\ 反斜槓()
單引號(’)
" 雙引號(")
\a ASCII響鈴(BEL)
\b ASCII退格(BS)
\f ASCII換頁(FF)
\n ASCII換行(LF)
\r ASCII回車(CR)
\t ASCII水平製表(TAB)
\v ASCII垂直製表(VT)
\ooo 八進位制值為ooo的字元 (注意點1,3)
\xhh 十六進位制值為hh的字元 (注意點2,3)

(2)只在字串字面值中識別的轉義序列是︰

轉義序列 含義 注意點
\N{name} Unicode資料庫中名為name的字元 (4)
\uxxxx 16位的十六進位制值為xxxx的字元 (5)
\Uxxxxxxxx 32位的十六進位制值為xxxxxxxx的字元 (6)

(3)注意點:

  1. 與標準C 一樣,最多接受三個八進位制數字。

  2. 與標準C 不同,要求兩個精確的十六進位制數字。

  3. 在字串字面值中,這些轉義表示給定的值的Unicode字元。

  4. 版本 3.3 中的更改︰名稱別名 [1] 支援已被新增。

  5. 四個十六進位制數字是必需的。

任何 Unicode 字元可以以這種方式被編碼。恰好八個十六進位制數字是必需的。

1.4 例子:

(1)定義字串:

def str_define():
    s1 = '單引號引起雙引號"內容"'
    s2 = "雙引號引起單引號'內容'"
    s3 = '''三引號引起"內容1",'內容2','''
    s4 = """三引號引起"內容1",'內容2',"""
    print(s1)
    print(s2)
    print(s3)
    print(s4)
#輸出結果
單引號引起雙引號"內容"
雙引號引起單引號內容''
三引號引起"內容1",'內容2',
三引號引起"內容1",'內容2',

(2)字首和轉義字元

def str_escape_prefix():
    s1 = 'hello\tMr,lengfengyuyu\nworld'
    s2 = 'hello\u0009Mr,lengfengyuyu\nworld'
    s3 = r'hello\tMr,lengfengyuyu\nworld'
    s4 = r'hello\u0009Mr,lengfengyuyu\nworld'
    s5 = u'hello\tMr,lengfengyuyu\nworld'
    s6 = u'hello\u0009Mr,lengfengyuyu\nworld'
    print("s1:",s1)
    print("s2:", s2)
    print("s3:", s3)
    print("s4:", s4)
    print("s5:", s5)
    print("s6:", s6)
# 輸出結果
s1: hello	Mr,lengfengyuyu
world
s2: b'hello\tMr,lengfengyuyu\n\xd6\xd0world'
s3: hello\tMr,lengfengyuyu\nworld
s4: hello\u0009Mr,lengfengyuyu\nworld
s5: hello	Mr,lengfengyuyu
world
s6: hello	Mr,lengfengyuyu
world

上面的結果能看出r字首的作用,但是u字首的作用不明顯,下面再解釋
(3)其他轉義內容:

def str_escape():
    s1 = 'hello\N{TAB}Mr,lengfengyuyu\nworld'
    s2 = 'i have \x61n apple & 5 \x62ananas & \141 pen'
    s3 = 'i have \u0061n apple & 5 \U00000062ananas & \141 pen'
    print("s1:",s1)
    print("s2:",s2)
    print("s3:",s3)
# 輸出結果
s1: hello	Mr,lengfengyuyu
world
s2: i have an apple & 5 bbananas & a pen
s3: i have an apple & 5 bbananas & a pen

2.方法

2.1 大小寫

首先定義一個字串s:
s = 'hello , Welcome to my worLd!ß'

str.capitalize()

功能:返回字串的一個副本,其首字母大寫,其餘的小寫。

s.capitalize() 
#輸出結果 
Hello , welcome to my world!ß

str.casefold()

功能:獲得字串小寫的副本。
版本:python 3.3中的新方法。
lower()方法很像,但是lower() 只對 ASCII 也就是 ‘A-Z’有效,但是其它一些語言裡面存在小寫的情況就沒辦法了,文件裡面舉得例子是德語中’ß’的小寫是’ss’。

Unicode標準的第3.13節描述了casefolding演算法。

s.casefold() 
#輸出結果 
hello , welcome to my world!ss

str.islower()

功能:如果字串中的所有字母字元都是小寫字母且至少有一個字元,則返回true,否則返回false。

def str_lower():
    s = '[email protected]#book'
    s1 = 'Book'
    print(s.islower())
    print(s1.islower())
#輸出結果
True
False

str.lower()

功能:返回原字串的副本,副本把所有字母字元轉換為小寫字母。

Unicode標準的第3.13節描述了使用的小寫字母轉換演算法。

def str_upper_lower():
    s1 = 'BOOK123'
    s2 = 'book123'
    print(s1.lower())
    print(s2.upper())
#輸出結果
book123
BOOK123

str.isupper()

功能:如果字串中的所有字母字元都是大寫且至少有一個字元,則返回true,否則返回false。

def str_upper():
    s = '[email protected]#book'
    s1 = 'BOOK123'
    print(s.isupper())
    print(s1.isupper())
#輸出結果
False
True

str.upper()

功能:返回原字串的副本,副本把所有字母字元轉換為大寫字母。
注意:str.upper().isupper()可能判斷有誤,因為字串可能含有非字母字元或者Unicode類的字元(非’Lu’,是’Lt’)。

Unicode標準的第3.13節描述了使用的大寫字母演算法。

def str_upper():
    s = '[email protected]#book'
    s1 = 'BOOK123ß'
    print(s.upper())
    print(s1.upper())
    print(s1.upper().isupper())
#輸出結果
123[email protected]#BOOK
BOOK123
True

str.swapcase()

功能:返回原始字串大小寫轉換之後的新字串(大小寫轉換)。

def str_swapcase():
    s = 'aBcDeFg,hh123'
    print(s.swapcase())
    print(s.swapcase().swapcase())
# 輸出結果
AbCdEfG,HH123
aBcDeFg,hh123

str.title()

功能:字串中單詞的首字母大寫,單詞中的其他部分變小寫。

def str_title():
    s = 'hello, mR lengYengYuyu'
    print(s.title())
    s = "hello, mR leng,they're bill's friends from the UK"
    print(s.title())
# 輸出結果
Hello, Mr Lengyengyuyu
Hello, Mr Leng,They'Re Bill'S Friends From The Uk

該演算法使用簡單的與語言無關的單詞作為連續字母組的定義。該定義在許多情況下都有效,但這意味著收縮和佔有者中的撇號會形成單詞邊界,這可能不是理想的結果,如上面的第二個輸出。
可以使用正則表示式構造撇號的解決方法:

def titlecase(s):
    return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
                  lambda mo:mo.group(0)[0].upper()+mo.group(0)[1:].lower(),
                  s)
def str_title():
    s = "hello, mR l,they're bill's friends from the UK"
    print(s.title())
    print(titlecase(s))
if __name__ == "__main__":
    str_title()
# 輸出結果
Hello, Mr L,They'Re Bill'S Friends From The Uk
Hello, Mr L,They're Bill's Friends From The Uk

2.2 顯示位置

str.center(width[, fillchar])

功能:返回以width為長度的字串,str在中心。填充是使用指定的fillchar完成的(預設是ASCII空格)。如果你指定的長度小於字串的長度,預設返回原始字串.

s.center(5)
s.center(50)
s.center(50,'-')
s.center(50, '中')
#輸出結果 
hello , Welcome to my worLd!ß
          hello , Welcome to my worLd!ß           
----------hello , Welcome to my worLd!ß-----------
中中中中中中中中中中hello , Welcome to my worLd!ß中中中中中中中中中中中

str.endswith(suffix[, start[, end]])

功能:如果字串以指定的suffix結尾則返回True,否則返回False。
suffix也可以是元組形式。使用可選的start,從該位置開始測試。使用可選的結束位置。

def str_endwidth():
    s = 'de encoding'
    print(s.startswith('g'))
    print(s.startswith(('g','d')))
    print(s.endswith('g'))
    print(s.endswith(('g','s')))
    print(s.endswith('g',len(s),len(s)+1))
# 輸出結果
False
True
True
True
False

str.startswith(prefix[, start[, end]])

功能:如果字串以prefix開頭則返回True,否則返回False。
prefix也可以是元組形式。使用可選的start,測試字串從該位置開始。使用可選的結束位置。引數用法同str.endswith()。

str.ljust(width[, fillchar])

功能:以width寬度的字串將字串左對齊。填充是使用指定的fillchar完成的(預設是ASCII空格)。如果指定的長度小於字串的長度,返回原字串.

def str_ljust():
    s = '*****'
    print(s.ljust(50,'-'))
    print(s.rjust(50, '-'))
    print(s.ljust(5,'-'))
# 輸出結果
*****---------------------------------------------
---------------------------------------------*****
*****

str.rjust(width[, fillchar])

功能:以width寬度的字串返回右對齊的字串。
引數用法同str.ljust()。

str.lstrip([chars])

功能:返回刪除前導字元的字串的副本。
chars引數是一個字串,用於指定要刪除的字符集。如果省略或None,chars引數預設為刪除空白。字元引數不是字首;相反,其值的所有組合都要被剝離,而且是貪婪的:

def str_strip():
    s= '\taa\tbcd'
    print(s.lstrip())
    s = 'aabcd'
    print(s.lstrip('a'))
    s = 'www.google.com'
    print(s.lstrip('abcdw.zgo'))
#輸出結果
aa	bcd
bcd
le.com

str.rstrip([chars])

功能:返回刪除尾隨字元的字串的副本。
引數用法同str.lstrip()。

str.strip([chars])

功能:返回刪除前導字元和尾隨字元的字串副本。
引數用法同str.lstrip()。

>>> comment_string = '#....... Section 3.2.1 Issue #32 .......'
>>> comment_string.strip('.#! ')
'Section 3.2.1 Issue #32'

str.expandtabs(tabsize=8)

功能:返回字串的副本,其中所有制表符由一個或多個空格替換,具體取決於當前列和給定製表符大小。
每個tabsize字元都會出現製表符位置(預設值為8,在列0,8,16等處提供製表位置)。要擴充套件字串,當前列設定為零,字串逐個檢查。如果該字元是一個製表符(\t),則在結果中插入一個或多個空格字元,直到當前列等於下一個製表符位置。(製表符本身不被複制。)如果該字元是換行符(\n)或返回(\r),則會將其複製並將當前列重置為零。任何其他字元都將被不變地複製,而當前列增加1,無論列印時字元如何表示。

s = 'what the\tff'
print(s.expandtabs())
print(s.expandtabs(2))
print(s.expandtabs(4))
print(s.expandtabs(8))
# 輸出結果
what the        ff
what the  ff
what the    ff
what the        ff
    

str.zfill(width)

功能:返回左側填充有ASCII 0位的字串的副本,以生成寬度為width的字串。
前導符號字首(’+’ / ‘-’)通過在符號字元後面插入填充符來處理,而不是在之前。指定的width超過字串的長度會返回原字串。

def str_fill():
    print("42".zfill(8))
    print("-42".zfill(8))
    print("--42".zfill(8))
    print("---42".zfill(8))
    print("+42".zfill(8))
    print("++42".zfill(8))
# 輸出結果
00000042
-0000042
-0000-42
-000--42
+0000042
+0000+42

例如:

2.3 子串查詢

str.find(sub[, start[, end]])

功能:返回在片段str[start:end]內找到子字串sub的字串中最小的索引。可選引數start和end被解釋為切片表示法。如果未找到sub,則返回-1。

注意只有當你需要知道sub的位置時,才應該使用find()方法。要檢查sub是否為子字串,請使用運算子中的in

s = 'wow, wow a cow'
print(s.find('ow'))
print(s.find('ow',2))
print(s.find('ow', 2,3))
print(s.find('ww', 2, 3))
print('cow' in s)
# 輸出結果
1
6
-1
-1
True

str.index(sub[, start[, end]])

功能:像find()一樣,但在找不到子字串時引發ValueError

def str_index():
    s = 'wow, wow a cow'
    print(s.index('ow'))
    print(s.index('ow',2))
    print(s.index('ww', 2, 3))
# 輸出結果
1
6
Traceback (most recent call last):
  File "xx/cu02-datatype-str.py", line 95, in str_index
    print(s.index('ww', 2, 3))
ValueError: substring not found

str.rfind(sub[, start[, end]])

功能:返回找到子字串sub的字串中的最大索引,使得sub包含在s[start:end]內。可選引數start和end被解釋為切片表示法。失敗時返回-1。

def str_replace():
    s = 'wow, wow a cow'
    print(s.rfind('w'))
    print(s.rfind('w',7,12))
    print(s.rindex('w'))
    print(s.rindex('w', 7, 12))
# 輸出結果
13
7
13
7

str.rindex(sub[, start[, end]])

功能:像上面的rfind()一樣,但當子字串sub未找到時引發ValueError

2.4 分割

str.split(sep=None, maxsplit=-1)

功能:在字串中,使用sep作為分隔符分割字串,返回分割後的列表。
如果給出maxsplit,則至多完成maxsplit分割(因此,列表最多隻能有maxsplit+1元素)。如果沒有指定maxsplit或-1,那麼分割數量沒有限制(所有可能的分割)。

如果給出了sep,則連續的分隔符不會分組在一起,並被視為分隔空字串(例如,'1,,2'.split(',')返回['1', '', '2'])。sep引數可以由多個字元組成(例如,'1<>2<>3'.split('<>')返回 ['1', '2', '3'])。用指定的分隔符分割空字串會返回[’’]。

def str_split():
    s = 'a.b.c.d.e.f.g'
    print(s.split('.'))
    print(s.split('.',maxsplit=2))
    s = 'a.b.c.d.e.f.g..'
    print(s.split(
            
           

相關推薦

Python 3.7.1 基礎-資料型別-字串

字串 1.基本內容 1.1 概念 1.2 構造方法 1.3 組成 1.3.1 轉義 1.4 例子: 2.方法 2.1 大小寫 str.capitali

Python 3.7.1 基礎 資料型別 列表 元組 字串

序列型別 1.前言 2.序列的通用操作 3. 序列型別 3.1 可變序列型別 3.1.1 列表 List 3.1.1.1 class list([iterable]) 3.1.1.2 s

Python 3.7.1 基礎 資料型別 集合 set

集合 1. 構造 2. 方法 2.1 set 和 frozenset的公有操作: len(s) x in s x not in s isdisjoint(other) issubset(o

Python 3.7.1 模組 資料型別 淺和深拷貝操作 copy

目錄 1. 需求描述 2. 模組方法 copy.copy(x) copy.deepcopy(x[, memo]) exception copy.error 3. 區別 3.1 普通例項 3.2

Python 3.7.1 模組 資料型別 高效的數值陣列 array

結構 1. 明確陣列型別 2. 定義 class array.array(typecode[, initializer]) 3.方法和常量 3.1 常量 array.typecodes 常量

Python 3.7.1 基礎-內建型別

內建型別 1.真值測試 2.布林運算 3.比較運算子 4.數值型別 4.1 操作運算子 4.2 整數的一些方法 int.bit_length() int.to_bytes(length, byteo

python精進之路1---基礎資料型別

python精進之路1---基本資料型別   python的基本資料型別如上圖,重點需要掌握字串、列表和字典。 一、int、float型別   int主要是用於整數型別計算,float主要用於小數。   int型別有個bit_length的方法。它用於返回二進位制表示是的位數。   

小白學 Python3):基礎資料型別(下)

人生苦短,我選Python 引言 前文傳送門 小白學 Python(1):開篇 小白學 Python(2):基礎資料型別(上) 前面我們介紹過了數字,本篇我們接著聊另一個常用的基礎資料型別:字串。 什麼是字串? 字串是由字元組成的一串有限序列,如: 'geekdigging' 、 "geek

python學習筆記02 --------------基礎資料型別

python的基本資料型別: 1.基本資料 1.1. 數字型別 1.1.1 整數 int int()           #將括號內內容轉化為整數型別。 1.1.2 浮點數 float 1.1.3 複數 complex  

python小課堂專欄】python小課堂06 - 基本資料型別字串運算篇

python小課堂06 - 基本資料型別字串運算篇 字串的運算 就題目而言,字串的運算?乍一看!這是什麼鬼?所謂的運算,數學定義的含義就是將數字之間進行各種演算法,例如加減乘除。那麼字串運算呢?同理:就是將字串進行所謂的“加減乘除! 當然如果在字串中獲取相關對應的字元,也算是

python小課堂專欄】python小課堂05 - 基本資料型別字串篇(重要)

python小課堂05 - 基本資料型別字串篇(重要) 什麼是字串? 題西林壁 作者:蘇軾 橫看成嶺側成峰,遠近高低各不同。 不識廬山真面目,只緣身在此山中。 如上面的詩詞一樣,將其對映到我們計算機程式中,顯然不是前幾張介紹的資料型別,那麼今天就來說下程式設計中

python學習日記(基礎資料型別02)-003

數字 int  :主要是用於計算的,常用的方法有一種 #既十進位制數值用二進位制表示時,最少使用的位數i = 3 s = i.bit_length() print(s)   布林值 bool  True/False while True: 等價於: whil

Python 3.7.1 模組 正則表示式 re

正則表示式操作 1. 正則表示式語法 1.1 特殊字元 . ^ $ * + ? *?,+?,?? {m} {m,n} {m,n}

Python 3.7.1 模組 string

string-常用string操作 1. 字串常量 string.ascii_letters string.ascii_lowercase string.ascii_uppercase string.digits stri

Python 3.7.1 官方文件 總結

Python 3.7.1 1.一些概念 2.小用法 2.1 迭代器: 2.2 生成器 3.資料結構 3.1 字串 3.2 列表 3.2.1 列表方法 list

Python 3.7.1 模組 併發執行 底層執行緒API _thread

底層執行緒API 1._thread 函式 exception _thread.error _thread.LockType _thread.start_new_thread(function, args[, kwargs]) _

Django專案:堡壘機(Linux伺服器主機管理系統)--01--01堡壘機重寫DJANGO賬戶表 python相關軟體安裝流程圖解————————python安裝——————python-3.7.1-amd64 python相關軟體安裝流程圖解————————pycharm安裝——————pyc

  python相關軟體安裝流程圖解————————python安裝——————python-3.7.1-amd64  https://www.cnblogs.com/ujq3/p/10098166.html   python相關軟體安裝流程圖解————————pyc

python學習筆記1資料型別

資料編碼 原碼、反碼、補碼 原碼:規定了位元組數,寫明瞭符號位,就得到了資料的原碼 反碼:正數的反碼是其原碼,負數的反碼是其原碼的符號位不動,其他位取反 補碼:正整數的補碼是其二進位制表示,與原碼相同,負整數的補碼,將其原碼除符號位外的所有位取反(0變1,1變0,符號位為1不變)後加1。

01.centos 7 安裝 python 3.7.1

make download orm gdbm python2 usr b- ncurses 查看 centos 7 安裝 python 3.7.1 https://www.python.org/downloads/source/ 在官網上下載 Python-3.7.1.ta

Python官網中,Python 3.7.1 的windows版本的區別

python官網有幾個下載檔案,有什麼區別? 1、進入Python官網http://www.python.org,在“Downloads”下拉選單中選擇相應的作業系統,我們選擇windows。 Python 3.7.1 - 2018-10-20 Download