使用Python可以通過多種方式操縱字符串。Python提供了各種函數、操作符和方法,可以用來操作字符串。您可以分割一個字符串,連接兩個或多個字符串,在字符串中**變量,等等。
Python中的字符串可以定義為一系列字符。它們是不可變的,這意味著一旦聲明它們就不能修改。相反,為操作目的創建字符串副本。
在Python中創建字符串就像在Python中為變量賦值一樣簡單。可以使用單引號(“”)、雙引號(“”)或三個單引號(“”)/雙引號(“”)來創建字符串。
str1 = 'Hello!'str2 = "Hello!"str3 = """Hello!"""str4 = '''Hello!'''print(str1)print(str2)print(str3)print(str4)輸出:
Hello!Hello!Hello!Hello!使用雙引號創建字符串的優點是,可以在雙引號內使用單引號字符。Python將單引號字符視為字符串的一部分。
s = "Using 'single quote' inside double quotes"print(s)輸出:
Using 'single quote' inside double quotes如果要創建多行字符串,那麼使用三個單引號(“”)/三個雙引號(“”)是最佳選擇。在使用單引號(“”)或雙引號(“”)創建字符串時,需要對新行使用轉義符(換行符)。但如果用三個引號,你就不需要這麼做了。
s1 = """This is a multilinestring using three double quotes"""s2 = "This is a multilinestring using double quotes"print(s1)print(s2)輸出:
This is a multilinestring using three double quotesThis is a multilinestring using double quotes如果要訪問單個字符,則使用索引;如果要訪問一系列字符,則使用切片。
與任何其他Python數據類型一樣,字符串索引從0開始。索引的範圍從0到字符串的長度-1。Python字符串還支持負索引:-1指向字符串的最後一個字符,-2指向字符串的最後第二個字符,依此類推。
s = "MAKEUSEOF"# Prints whole stringprint(s)# Prints 1st characterprint(s[0])# Prints 2nd characterprint(s[1])# Prints last characterprint(s[-1])# Prints 2nd last characterprint(s[-2])輸出:
MAKEUSEOFMAFO您必須使用整數訪問字符否則,您將得到一個TypeError。如果您試圖訪問超出範圍的元素,也會發生這種情況。
類型錯誤:
s = "MAKEUSEOF"# TypeError will be thrown if you don't use integersprint(s[1.5])輸出:
TypeError: string indices must be integers索引器:
s = "MAKEUSEOF"# IndexError will be thrown if you try to use index out of rangeprint(s[88])輸出:
TypeError: string indices must be integers可以使用冒號運算符(:)訪問一系列字符。
s = "MAKEUSEOF"# Prints from 0th index(included) to 4th index(excluded)print(s[0:4])# Prints from 3rd last index(included) to last index(excluded)print(s[-3:-1])# Prints from 2nd index to last of the stringprint(s[2:])# Prints from start of the string to 6th index(excluded)print(s[:6])輸出:
MAKEEOKEUSEOFMAKEUS+運算符用於連接兩個或多個字符串。它返回結果串聯字符串。
s1 = "MAKE"s2 = "USE"s3 = "OF"s = s1 + s2 + s3# Prints the concatenated stringprint(s)輸出:
MAKEUSEOF用於將字符串重複給定次數。
str = "MUO-"# Prints str 5 timesprint(str * 5)# Prints str 2 timesprint(2 * str)x = 3# Prints str x times# Here, x = 3print(str * x)輸出:
MUO-MUO-MUO-MUO-MUO-MUO-MUO-MUO-MUO-MUO-這是一個成員運算符,用於檢查第一個操作數是否存在於第二個操作數中。如果第一個操作數出現在第二個操作數中,則返回True。
否則返回False。
str = "MAKEUSEOF"# Returns True as MAKE is present in strprint("MAKE" in str)# Returns False as H is not present in strprint("H" in str)輸出:
TrueFalse另一個成員操作符,not in與in操作符相反。如果第一個操作數出現在第二個操作數中,則返回False。否則返回True。
str = "MAKEUSEOF"# Returns True as Hello is not present in strprint("Hello" not in str)# Returns False as M is present in strprint("M" not in str)輸出:
TrueFalse使用轉義序列可以在字符串中放置特殊字符。您只需在要轉義的字符之前添加一個反斜槓(/)。如果不轉義字符,Python將拋出一個錯誤。
s = 'We are using apostrophe \' in our string'print(s)輸出:
We are using apostrophe ' in our string通過在花括號中**變量,可以在字符串內部使用變量。此外,在打開字符串的引號之前,還需要添加小寫f或大寫f。
s1 = "Piper"s2 = "a"s3 = "pickled"str = f"Peter {s1} picked {s2} peck of {s3} peppers"# s1, s2 and s3 are replaced by their valuesprint(str)a = 1b = 2c = a + b# a, b and c are replaced by their valuesprint(f"Sum of {a} + {b} is equal to {c}")輸出:
Peter Piper picked a peck of pickled peppersSum of 1 + 2 is equal to 3此函數用於查找字符串的長度。它是Python中最常用的函數之一。
str = "MAKEUSEOF"# Prints the number of characters in "MAKEUSEOF"print(len(str))輸出:
9同時該函數用於查找字符的整數值。Python是一種通用語言,它支持ASCII和Unicode字符。
c1 = ord('M')c2 = ord('a')c3 = ord('A')c4 = ord('$')c5 = ord('#')print(c1)print(c2)print(c3)print(c4)print(c5)輸出:
7797653635使用chr()查找整數的字符值。
i1 = chr(77)i2 = chr(97)i3 = chr(65)i4 = chr(36)i5 = chr(35)print(i1)print(i2)print(i3)print(i4)print(i5)輸出:
MaA$#相關:什麼是ASCII文本,它是如何使用的?
使用此函數可以將任何Python對象轉換為字符串。
num = 73646# Converts num (which is integer) to strings = str(num)# Prints the stringprint(s)# Type functi*** returns the type of object# Here, <class 'str'> is returnedprint(type(s))輸出:
73646<class 'str'>可以使用split()方法將字符串拆分為基於分隔符的字符串列表。
str1 = "Peter-Piper-picked-a-peck-of-pickled-peppers"splitted_list1 = str1.split('-')# Prints the list of strings that are split by - delimiterprint(splitted_list1)str2 = "We surely shall see the sun shine soon"splitted_list2 = str2.split(' ')# Prints the list of strings that are split by a single spaceprint(splitted_list2)輸出:
['Peter', 'Piper', 'picked', 'a', 'peck', 'of', 'pickled', 'peppers']['We', 'surely', 'shall', 'see', 'the', 'sun', 'shine', 'soon']可以使用join()方法連接iterable對象的所有元素。可以使用要加入元素的任何分隔符。
list1 = ["I", "thought", "I", "thought", "of", "thinking", "of", "thanking", "you"]# Joins the list as a string by using - as a delimiterstr1 = "-".join(list1)print(str1)list2 = ["Ed", "had", "edited", "it"]# Joins the list as a string by using a single space as a delimiterstr2 = " ".join(list2)print(str2)輸出:
I-thought-I-thought-of-thinking-of-thanking-youEd had edited it處理字符串和文本是編程不可或缺的一部分。字符串充當從程序向程序用戶傳遞信息的媒介。使用Python可以按照您想要的方式操縱字符串。
...式語言,它可以用於各種應用程式。Python廣泛應用於機器學習、資料科學、科學計算等領域。它還用於web開發、聯網和編寫自動化指令碼。它可以用於影象處理和自然語言處理中的演算法開發。 Raspberry pi是一款基於Linux作業系統...
...它是一種跨平臺、開源的語言。Python程式更容易讀、寫和學習。這些程式也很容易測試和除錯。Python是初學者的首選程式語言,因為它簡單。Python是一種多範例程式語言。它主要支援過程式和麵向物件的程式語言。 Python是一種...
...自己的結構和行為。因此,它具有反射性。 Ruby語法易於學習和閱讀。沒有太多複雜的語法、命名和行為。Ruby語法與英語語言相似,程式設計師容易理解,因此被歸類為高階程式語言。程式設計師可以理解的ruby程式透過直譯器...
...的多正規化。蟒蛇是圭多·範羅森發現的。它是一種易於學習的程式語言,可用於各種應用程式。Python有兩個主要版本,分別是python2和python3。本文將討論這兩個版本之間的差異。Python2和3之間的關鍵區別在於,Python2在未來將獲...
...果您是Python的新手,那麼您可能仍然需要採用某種方法來學習。因此,讓我們透過本文了解如何使用Python複製檔案。 ...
在Python中及時使用列表理解可以使迭代列表操作變得容易。除了一行之外,它的可讀性更高,執行效率也更高。 ...
...們被禁止,但在C++中可用。其他語言(如Java、JavaScript、python等)不提供類似的功能。 ...
...執行的C++編寫的應用程式可以輕鬆地將JSON資料與應用於Python的應用程式進行執行,並在Linux上執行。它的簡單性和靈活性近年來得到了廣泛的應用,特別是在更傾向於早期基於XML的格式方面。 ...
...DIY智慧家居技術,但在Raspberry Pi上程式設計提供了大量的學習機會。 ...