創(chuàng)建
s1 = 'shark'
s2 = "shark"
s3 = """hello shark"""
s4 = '''hello shark'''
s5 = """hello
shark
"""
簡(jiǎn)單操作
\ 轉(zhuǎn)義符
testimony = 'This shirt doesn\'t fit me'
words = 'hello \nworld'
+拼接
print('hello' + 'world')
不可以用 字符串和 一個(gè)非字符串類型的對(duì)象相加
'number' + 0 # 這是錯(cuò)誤的
* 復(fù)制
print('*' * 20)
print('shark' * 20)
字符串 和 0 或者 負(fù)數(shù)相乘,會(huì)得到一個(gè)空字符串
In [76]: 'hey' * 0
Out[76]: ''
In [77]: 'hey' * -3
Out[77]: ''
進(jìn)階操作
認(rèn)識(shí) Python 中第一個(gè)數(shù)據(jù)結(jié)構(gòu) 序列類型
-
存放的數(shù)據(jù),在其內(nèi)是有序的,內(nèi)部的數(shù)據(jù)是可以通過在其
內(nèi)部所處的位置進(jìn)行訪問等操作。
字符串型就是 python 序列類型的數(shù)據(jù)結(jié)構(gòu)中的一種,本質(zhì)是
字符序列
序列類型的特點(diǎn)
序列里的每個(gè)數(shù)據(jù)被稱為序列的一個(gè)元素
-
元素在序列里都是有個(gè)自己的位置的,這個(gè)位置被稱為索引或
者叫偏移量,也有叫下標(biāo)的
下標(biāo)偏移量從 0 開始到序列整個(gè)元素的個(gè)數(shù)減去1結(jié)束
序列中的每一個(gè)元素可以通過這個(gè)元素的偏移量(索引)來獲取到
而多個(gè)元素需要用切片的操作來獲取到
s1 = "shark"

image
獲取元素
# 獲取單個(gè)元素
s1[0]
s1[3]
s1[-1]
切片

image
# 使用切片獲取多個(gè)元素
s1[0:2]
下面這樣的操作,是的不到我的
s1[-1:-3]
# 獲取字符串的長(zhǎng)度,包含空格和換行符
len(s1)
利用字符串對(duì)象的方法
split
url = 'www.qfedu.com 千鋒官網(wǎng)'
url.split()
li = url.split('.')
host, *_ = url.split('.', 1)
rsplit 從右向左分割
url = 'www.qfedu.com'
url2 = url.rsplit('.', 1)
replace 替換
url = 'www.qfedu.com'
url2 = url.replace('.', '_')
strip 移除兩端的空格
s = ' hello '
s2 = s.strip()
inp = input(">:").strip()
s = "symbol=BCHBTC;baseCoin=BCH;quoteCoin=BTC;"
s_list = s.split(';')
# print(s_list)
# ['symbol=BCHBTC', 'baseCoin=BCH', 'quoteCoin=BTC', '']
startswith 判斷字符串以什么為開頭
s = 'hello world'
if s.startswith('h'):
print(s)
endswith 判斷字符串以什么為結(jié)尾
s = 'hello world'
if s.endswith('d'):
print(s)
index 獲取一個(gè)元素在字符串中的索引號(hào)
s = 'hello world'
idx = s.index('l')

image

image

image
交互輸入

image