python學習2 使用字串

2022-05-02 16:51:08 字數 1432 閱讀 6071

字串

所有標準的額序列操作(索引,分片,乘法,判斷成員資格,求長度,最大最小值) 對字串都適用,但,字串是不可變的

>>> a  = 'my name is hahaahh'

>>> a[:3] = 'sdsd'traceback (most recent call last):

file "", line 1, in a[:3] = 'sdsd'typeerror: 'str' object does not support item assignment

字串格式串 --精簡版

字串格式化適用字串格式化操作符即百分號% 來實現

--格式化字串  %s

>>> format = 'hello ,%s,%s enough for you'

>>> values = ('haha','zhang')

>>> print format %values

hello ,haha,zhang enough for you

如果要 格式化 是實數 則用   %f

格式化字串 --完整版

pass

字串方法  --列舉一些 特別有用的

find -可以在乙個較長的字串中查詢子串,返回子串所在位置最左端索引,如果沒有找到 返回 -1

>>> a = "zhang is a good boy"

>>> a.find("is")

6>>> a.find("cheng")

-1>>> "zhang is a ".find("a")

2

join --用來連線序列中的元素(元素 必須都是字串) ,是 split 的逆方法 

>>>seq = ["1","2","3"]

>>> sep ="+"

>>>sep.join(seq)

'1+2+3'

lower  --返回字串的小寫字母版

replace --返回某字串的所有匹配項均被替換後的字串

>>> 'this is a boy'.replace('is','kk')

'thkk kk a boy'

split --將字串分割成序列 是 join 的逆方法

>>> '1+2+3+4+5'.split('+')

['1', '2', '3', '4', '5']

#如果不提供分隔符,則將 空格 作為 分隔符

>>> "i am a boy".split()

['i', 'am', 'a', 'boy']

strip --去除兩邊的空格

translate --可以替換字串的某些部分,但和 replace 不同的是 他只處理單個字元

python學習Day2 使用字串

1 字串都是不可變的 2 字串格式化 format hello,s.s enough for ya?values world hot print format values hello,world.hot enough for ya?format pi with three decimal 3f f...

python基礎知識(2) 使用字串

在這裡會介紹使用字串格式化其他值,並簡單了解一下利用字串的分割 連線 搜尋等方法能做些什麼。基本字串操作 所有標準的序列操作 索引 分片 乘法 判斷成員資格 求長度 取最大值 取最小值 同樣適用。字串是不可變的,下面看乙個例項說明這點。website website 3 com traceback ...

Python學習day7 使用字串

申明 本文為練習python使用,跟隨github上jackfrued的python 100 days,邊學邊練 def main str1 hello,world 通過len函式計算字串長度 print len str1 獲得字串首字母大寫的拷貝 print str1.capitalize 獲得字...