1. 程式人生 > >Python字串string的查詢和替換

Python字串string的查詢和替換

hello_str = "hello world"
# 1. 判斷空白字元
space_str = "      \t\n\r"
print(space_str.isspace())

# 2. 判斷是否以指定字串開始
print(hello_str.startswith("hello"))

# 3. 判斷是否已指定字串結束
print(hello_str.endswith("world"))

# 4. 查詢字串
print(hello_str.find("llo"))
print(hello_str.find("abc"))# find 指定字串不存在會返回-1
# 注意:index 指定字串不存在會報錯

# 5. 替換字串
# replace方法執行完成後,會返回一個新的字串
# 注意:不會修改原有字元的內容
print(hello_str.replace("world", "python"))
print(hello_str)

輸出: True True True 2 -1 hello python hello world