共計 752 個字符,預計需要花費 2 分鐘才能閱讀完成。
Python 中 str 是一種字符串類型的數據結構,用于表示文本信息??梢酝ㄟ^以下方式使用 str:
- 創建一個字符串對象:
s = "Hello, World!"
- 訪問字符串中的字符:
print(s[0]) # 輸出:H
- 獲取字符串的長度:
print(len(s)) # 輸出:13
- 字符串切片:
print(s[7:12]) # 輸出:World
- 字符串拼接:
s1 = "Hello"
s2 = "World"
s3 = s1 + "," + s2
print(s3) # 輸出:Hello, World
- 字符串格式化:
name = "Alice"
age = 25
print("My name is %s and I'm %d years old."% (name, age)) # 輸出:My name is Alice and I'm 25 years old.
- 字符串查找和替換:
s = "Hello, World!"
print(s.find("World")) # 輸出:7
print(s.replace("Hello", "Hi")) # 輸出:Hi, World!
- 字符串大小寫轉換:
s = "Hello"
print(s.lower()) # 輸出:hello
print(s.upper()) # 輸出:HELLO
- 字符串分割和連接:
s = "Hello, World!"
print(s.split(",")) # 輸出:['Hello', 'World!']
print("".join(['Hello','World!'])) # 輸出:Hello World!
- 判斷字符串是否以指定的前綴或后綴開始 / 結束:
s = "Hello, World!"
print(s.startswith("Hello")) # 輸出:True
print(s.endswith("World!")) # 輸出:True
這些是常見的字符串操作方法,可以根據需要來使用。
丸趣 TV 網 – 提供最優質的資源集合!
正文完