一、字元串創建
在Python中,可以使用單引號、雙引號或三引號來創建字元串。單引號和雙引號用法相同,而三引號可以用來創建多行字元串。
>>> str1 = 'hello'
>>> str2 = "world"
>>> str3 = """This is
a multi-line
string."""
如果想在字元串中包含引號,可以使用單引號和雙引號互相嵌套,或者使用轉義符號「\」。
>>> str4 = "She said, \"I'm fine.\""
>>> str5 = 'He said, \'It\'s okay.\''
>>> str6 = "I\'m learning Python."
二、字元串連接
可以使用「+」符號將兩個字元串連接起來,並使用「*」符號實現字元串的重複。
>>> str1 = "hello"
>>> str2 = "world"
>>> str3 = str1 + " " + str2
>>> str4 = "ha " * 3
>>> print(str3) # 輸出 "hello world"
>>> print(str4) # 輸出 "ha ha ha "
三、字元串分割和拼接
使用split函數可以將一個字元串按照指定分隔符進行拆分,然後使用join函數將拆分後的字元串列表重新拼接成一個字元串。
>>> str1 = "apple,banana,orange"
>>> list1 = str1.split(",")
>>> str2 = "-".join(list1)
>>> print(list1) # 輸出 ['apple', 'banana', 'orange']
>>> print(str2) # 輸出 "apple-banana-orange"
四、字元串查找和替換
在Python中,可以使用find函數和index函數查找字元串中指定子串的位置,並使用replace函數替換指定子串。
>>> str1 = "hello world"
>>> print(str1.find("world")) # 輸出 6
>>> print(str1.index("l")) # 輸出 2
>>> str2 = str1.replace("world", "Python")
>>> print(str2) # 輸出 "hello Python"
五、字元串大小寫轉換
可以使用lower函數將字元串轉換為小寫字母,使用upper函數將字元串轉換為大寫字母。
>>> str1 = "Hello World"
>>> str2 = str1.lower()
>>> str3 = str1.upper()
>>> print(str2) # 輸出 "hello world"
>>> print(str3) # 輸出 "HELLO WORLD"
六、字元串格式化
在Python中,可以使用佔位符來格式化字元串,常用的佔位符包括%s(字元串)、%d(整數)、%f(浮點數)等。
>>> str1 = "My name is %s, I'm %d years old."
>>> print(str1 % ("Alice", 20)) # 輸出 "My name is Alice, I'm 20 years old."
七、字元串判斷函數
Python中提供了一些函數用來判斷字元串的屬性,例如字元串是否以指定子串開始、是否以指定子串結束、是否由數字組成等。
>>> str1 = "hello world"
>>> print(str1.startswith("hello")) # 輸出 True
>>> print(str1.endswith("world")) # 輸出 True
>>> print(str1.isdigit()) # 輸出 False
八、總結
Python的str函數提供了豐富的文本處理功能,包括字元串創建、連接、分割和拼接、查找和替換、大小寫轉換、格式化和判斷函數等。可以根據具體情況選擇相應的函數,完成文本處理任務。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/187637.html