python中用’ '和" "創建字符串
python的子字符串截取用[]取
字符串拼接可以直接用+相加。
python三引號允許一個字符串跨多行,其中無需進行轉義(所見即所得)。
當你需要一塊HTML或者SQL時,這時用字符串組合,特殊字符串轉義將會非常的繁瑣。
format 格式化函數
>>>"{} {}".format("hello", "world") # 不設置指定位置,按默認順序
'hello world'>>> "{0} {1}".format("hello", "world") # 設置指定位置
'hello world'>>> "{1} {0} {1}".format("hello", "world") # 設置指定位置
'world hello world'
也可以設置參數
#!/usr/bin/python
# -*- coding: UTF-8 -*-print("網站名:{name}, 地址 {url}".format(name="菜鳥教程", url="www.runoob.com"))# 通過字典設置參數
site = {"name": "菜鳥教程", "url": "www.runoob.com"}
print("網站名:{name}, 地址 {url}".format(**site))# 通過列表索引設置參數
my_list = ['菜鳥教程', 'www.runoob.com']
print("網站名:{0[0]}, 地址 {0[1]}".format(my_list)) # "0" 是必須的
f—string,過去通過%替換變量
>>> name = 'Runoob'
>>> 'Hello %s' % name
'Hello Runoob'
f—string,現在通過f標識字符串,更加簡單,不用判斷是%s還是%d
>>> name = 'Runoob'
>>> f'Hello {name}' # 替換變量
'Hello Runoob'
>>> f'{1+2}' # 使用表達式
'3'>>> w = {'name': 'Runoob', 'url': 'www.runoob.com'}
>>> f'{w["name"]}: {w["url"]}'
'Runoob: www.runoob.com'
在 Python 3.8 的版本中可以使用 = 符號來拼接運算表達式與結果:
>>> x = 1
>>> print(f'{x+1}') # Python 3.6
2>>> x = 1
>>> print(f'{x+1=}') # Python 3.8
x+1=2
在Python3中,所有的字符串都是Unicode字符串。
檢測 str 是否包含在字符串中,如果指定范圍 beg 和 end ,則檢查是否包含在指定范圍內,如果包含返回開始的索引值,否則返回-1
find(str, beg=0, end=len(string))
index(str, beg=0, end=len(string))#同上,但如果不在會拋異常
返回 str 在 string 里面出現的次數,如果 beg 或者 end 指定則返回指定范圍內 str 出現的次數
count(str, beg= 0,end=len(string))
返回字符串長度
len(string)