定義字串
string =
''string1 =
'this is a string'
string2 = r'this is a raw string'
# 原始字串, 轉義字元等均不轉義原樣輸出
獲取字串長度length =
len(string1)
print
(length)
# 16
字串判斷if
'is'
in string1:
print
('string1 含有 `is`'
)if string1 == string2:
print
('string1 與 string2 一樣'
)
字串拼接n_str =
'this is '
+'a string'
# 使用 `+` 拼接
print
(n_str)
# this is a string
n_str =
'this is '
n_str +=
'a string'
# 使用 `+=` 拼接
print
(n_str)
# this is a string
n_str2 =
'num: '
+str(4
)# 拼接數字
print
(n_str2)
# num: 4
設定字串格式format_str =
'%s is a string. length: %d'%(
'this',16
)# 格式化, %f、%d、%s等格式, 和 c 語言基本上一致
print
(format_str)
# this is a string. length: 16
format_str =
'th{} a '
.format
('is'
, p2=
'string'
, p1=
'is'
)# format_str = 'th a '.format(p2='string', p1='is')
# format_str = 'th a '.format('string', 'is')
# format_str = ' is a '.format('this', 'string')
# format_str = '{} is a {}'.format('this', 'string')
print
(format_str)
# this is a string
基本轉換t_str =
'the number is '
.format
(num=88)
print
(t_str)
# the number is 88
t_str =
'the number is '
.format
(num=88)
# 浮點型
print
(t_str)
# the number is 88.000000
t_str =
'the number is '
.format
(num=88)
# 浮點型-保留2位小數
print
(t_str)
# the number is 88.00
t_str =
'the number is '
.format
(num=88)
# 浮點型-保留2位小數,指定寬度, 如果不足則在前面補0
print
(t_str)
# the number is 0000088.00
t_str =
'the number is '
.format
(num=88)
# 二進位制
print
(t_str)
# the number is 1011000
字串簡單切片(擷取),高階切片此文暫時不介紹,以後會開新文章介紹
python 分正索引與負索引, 正索引和其他程式語言一樣;負索引是從最後往前標識, 負索引是從-1
開始的
切片格式:str[擷取開始索引:擷取結束索引]
t_str = string1[:-
3]# 從索引0開始擷取到倒數第三個字元之前的位置
# t_str = string1[0:-3]
print
(t_str)
# this is a str
t_str = string1[:3
]# 從索引0開始擷取到索引3字元之前的位置
# t_str = string1[0:3]
print
(t_str)
# thi
t_str = string1[5:
7]# 從索引5開始擷取到索引7之前的位置
print
(t_str)
# is
字串分割與拼接array = string1.split(
' ')
# 以空格分割字串
print
(array)
# ['this', 'is', 'a', 'string']
t_str =
'-'.join(array)
# 以 `-` 將字串陣列拼接成字串
print
(t_str)
# this-is-a-string
大小寫轉換upp = string1.upper(
)# 轉為大寫
print
(upp)
# this is a string
low = upp.lower(
)# 轉為小寫
print
(low)
# this is a string
去掉字串前後的空白,不包含中間的空白t_str =
' \n\n this is a string \n'
.strip(
)print
(t_str)
# this is a string
查詢子字串index = string1.find(
'is a'
)# 如果查詢到子字串則返回子串的第乙個字元的索引,否則返回 `-1`
print
(index)
# 5
替換字串t_str = string1.replace(
'string'
,'raw string'
)print
(t_str)
# this is a raw string
遍歷字串for char in string1:
print
(char)
'''thi
s is
a strin
g'''
Python3 7總結字串的print和拼接
4.格式化字串f 5.format 格式化字串 a qq b tx c 28129019 d 28129019 print a print b print c print type d print d 控制台輸出結果 qqtx 28129019 28129019a qq b tx c 2812901...
學python(08) 字串函式
字串函式 用字串中的指定字元切割字串split result strs.split 輸入 n 代表用換行分割 用回車進行字串分割splitlines result strs.splitlines 用指定的字串將容器內的字串鏈結成乙個字串 joinresult join lists 0填充函式zfil...
python學習 str字串
s hello world print s s hello world print s s hello world print s 轉義字元案例 想表達let s go 使用轉義字元 s let s go 就想表達乙個單引號,不想組成引號對 print s 表示斜槓 比如表示c user augsn...