字串的一些處理
字串的大小寫
輸出結果將是name=
"lonmar hb"
(name.upper())
#全大寫
(name.lower())
#全小寫
(name.title())
#每個單詞首字母大寫
合併字串
用+來拼接兩個字元first_name=
"qwq"
last_name=
"lovl"
full_name=first_name+
" "+last_name
(full_name)
上述**結果
字串中的空白處理
執行結果("python"
("python "
("\tpython"
)#\t為製表符 tab
("\npython\nhh"
)# \n為換行符
刪除空白
強制轉換成字串test=
" abcdefghijk "
(test)
(test.rstrip())
#剔除右邊的空白
(test.lstrip())
#剔除左邊的空白
(test.strip())
#剔除兩邊的空白
str()
#下面是一段錯誤**
age=
23message =
+ age +
"rd birthday!"
(message)
#此時會報錯 typeerror: can't convert 'int' object to str implicitly
#下面是正確的**
age =
23 message =
+str
(age)
+"rd birthday!"
(message)
#這裡包含了強制型別轉換,將整形轉變成了字串型別
列表方法chars.upper(
)chars.lower(
)chars.title(
)chars1+chars2
\t tab
\n enter
chars.lstrip(
)刪除左空白
chars.rstrip(
)刪除右空白
chars.strip(
)刪除兩邊空白
str(
)強制轉換成字串
在列表中新增元素
在列表中插入元素demo1:
animals =
['dogs'
,'cats'
]'sheep'
(animals)
>
['dogs'
,'cats'
,'sheep'
]demo2:
animals =
#建立乙個空列表
'dog'
)'cat'
(animals)
>
['dogs'
,'cats'
]
使用insert放法
刪除列表中的元素animals =
['dogs'
,'cats'
]animals.
insert(0
,'sheep'
(animals)
>
['sheep'
,'dogs'
,'cats'
]
del語句
pop方法來儲存刪除的元素animals =
['sheep'
,'dogs'
,'cats'
]del animals[0]
(animals)
>
['dogs'
,'cats'
]
remove方法animals =
['sheep'
,'dogs'
,'cats'
]animals_pop = animals.
pop(1)
(animals_pop)
(animals)
>dogs
>
['sheep'
,'cats'
]# 使用pop不僅能刪除列表中指定的元素,還能定義乙個變數儲存該元素
可以從列表中移除未知索引的元素
sort()方法對列表永久性排序animals =
['sheep'
,'dogs'
,'cats'
]animals.
remove
('dogs'
)# 從列表中移除了dogs
# 但remove只移除了第乙個指定的值,移除全部的值必須用迴圈
sorted()方法對列表進行臨時排序demo1:
cars =
['bmw'
,'audi'
,'toyota'
,'subaru'
] cars.
sort()
(cars)
>
['audi'
,'bmw'
,'subaru'
,'toyota'
] # 按照首字母的順序對列表進行排序
demo2:
# 還可以對列表元素進行逆排序
cars =
['bmw'
,'audi'
,'toyota'
,'subaru'
]cars.
sort
(reverse=true)
(cars)
>
['toyota'
,'subaru'
,'bmw'
,'audi'
]
reverse()反轉列表cars=
['toyota'
,'subaru'
,'bmw'
,'audi'
(cars.
sorted()
(cars)
>
['audi'
,'bmw'
,'subaru'
,'toyota'
]>
['toyota'
,'subaru'
,'bmw'
,'audi'
]
len()確定列表的長度animals=
['dogs'
,'cats'
,'sheeps'
]animals.reverse
(animals)
>
['sheeps'
,'cats'
,'dogs'
]# 純粹的將列表中元素的順序反過來
len
(animals)
>
3
list
)# 像列表中最後乙個位置新增元素
list
.insert(num,
'element'
)# 向列表某個位置插入元素
del(element)
#刪除列表中的某個元素
pop(num_index)
# 刪除指定索引的元素,並且還能用另乙個變數儲存該元素
remove(element)
# 刪除指定的元素,但僅僅刪除列表中第乙個element
sort(
)# 對列表中的元素進行永久排序 reverse = true 則進行逆序排序
sorted()
# 對列表中的元素進行暫時排序
reverse(
list
)#將列表中的元素反轉
len(
list
)# 確定列表中的元素個數
python學習筆記(一) 字串
字串是python中最常用的資料型別。我們可以使用引號 或 來建立字串。建立字串很簡單,只要為變數分配乙個值即可。例如 var1 hello var2 world python不支援單字元型別,單字元在python中也作為乙個字串使用。python訪問子字串,可以使用方括號來擷取字串,例如 通過索引...
python語法筆記(一)字串專題
字串翻轉 方法1 str 123 print str str join reversed str print str 方法2 str 123 print str str str 1 print str 字串去空格 特殊字元 s hello,world hh print s,print s.strip...
字串(一) 字串Hash
今天開一手最不 tao 擅 yan 長的字串演算法 字串hash演算法。似乎提到字串的話,kmp應該是更為常見的一種,但是hash有它的優點,被犇們稱為 優雅的暴力 何謂hash?hash的中文稱為雜湊,這當然是音譯,直譯過來就是雜湊,或者也有叫預對映的。雜湊的作用就是通過某個特殊函式的對映,將任意...