Python中的字元串類型是str,是一種不可變的序列。字元串操作在字元串處理中是至關重要的,了解如何操作它們是必須的。
一、檢測字元串
在Python中,可以使用許多字元串方法來檢測字元串。這些方法提供了許多開箱即用的函數,用於確定字元串的一些特性。
1、判斷是否以指定字元串開始或結束:
s = "Hello, world!"
print(s.startswith("Hello")) # True
print(s.endswith("world!")) # True
2、檢測字元串是否僅包含字母、數字等(isalnum)、字母(isalpha)、數字(isdigit)等:
s1 = "abc123"
s2 = "abc"
s3 = "123"
print(s1.isalnum()) # True
print(s2.isalpha()) # True
print(s3.isdigit()) # True
二、字元串的搜索和替換
字元串操作中另一個重要的方面是搜索和替換字元串。Python提供了各種方法來搜索和替換字元串,包括使用正則表達式和使用Python內置的字元串模塊。
1、搜索字元串:
s = "The quick brown fox jumps over the lazy dog."
print(s.find("fox")) # 16
print(s.index("xyz")) # 報錯,因為"xyz"未在字元串中找到
2、使用replace()方法替換字元串:
s = "Hello, world!"
print(s.replace("world", "Python")) # Hello, Python!
三、連接和分割字元串
在Python中,有許多方法用於連接和分割字元串。
1、連接字元串:
s1 = "Hello"
s2 = "world"
print(f"{s1} {s2}") # Hello world
print(s1 + " " + s2) # Hello world
2、分割字元串:
s = "apple,banana,orange"
print(s.split(",")) # ['apple', 'banana', 'orange']
四、修改字元串大小寫
Python提供了許多字元串方法,可以在字元串中更改大小寫。
1、轉換為大寫/小寫:
s = "Hello, world!"
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
2、首字母大寫/小寫:
s = "hello, world!"
print(s.capitalize()) # Hello, world!
print(s.title()) # Hello, World!
五、刪除字元串空格
Python提供了各種方法來刪除字元串開頭和結尾的空格或全局空格。
1、刪除開頭和結尾的空格:
s = " Hello, world! "
print(s.strip()) # Hello, world!
print(s.lstrip()) # Hello, world!
print(s.rstrip()) # Hello, world!
2、刪除所有空格:
s = " Hello, world! "
print(s.replace(" ", "")) # Hello,world!
print("".join(s.split())) # Hello,world!
六、格式化字元串
Python中有幾種方法可以格式化字元串。其中一種最常用的方法是使用字元串格式化。
1、使用字元串格式化:
name = "Alice"
age = 25
print("My name is %s. I am %d years old." % (name, age)) # My name is Alice. I am 25 years old.
2、使用f-strings:
name = "Alice"
age = 25
print(f"My name is {name}. I am {age} years old.") # My name is Alice. I am 25 years old.
七、字元串長度
可以使用len()函數計算字元串的長度。
s = "Hello, world!"
print(len(s)) # 13
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/304290.html