Python字串常用方法

2021-09-11 04:17:50 字數 1511 閱讀 2335

count():獲取字串中某個字元的數量。

str = 'python_count'

str.count('o')

>>> 2

strip():刪除字串首位的空格,以及換行。

str1 = '   hello python   '

str2 = 'hello python '

str3 = ' hello python'

str1.strip()

str2.strip()

str3.strip()

>>> 'hello python'

split():預設情況下在字串中有空格的位置將字串切割生成乙個列表,有引數時,在引數處進行切割。

str1 = 'hello python'

str2 = 'hello,python'

str3 = 'hellopython'

lst1 = str1.split()

lst2 = str2.split(',')

lst3 = str3.split('o')

print(lst1,lst2,lst3)

>>> ['hello','python'] ['hello','python'] ['hell','pyth','n']

upper() & lower():前者將字串中每個英文變成大寫,後者將字串中每個英文變成小寫。

str = 'hello_python'

str.upper()

>>> 'hello_python'

str.lower()

>>> 'hello_python'

__len__():相當於內建函式len(),獲得字串包括字元的數量。

str = 'hello python'

str.__len__()

>>> 12

>>>'hello python'.__len__()

>>> 12

len(str)

>>> 12

str.format():格式化字串函式

#將引數依次填入字串中

>>>'{} {}'.format(hello,python)

>>> 'hello python'

#規定每個位置傳入引數

>>>' , '.format(hello,world,python)

>>> 'hello world,hello python'

#格式化浮點(float)型別引數為字串,並規定小數字數

str = ''.format(math.pi)

print(str)

>>> 3.14

#通過字典設定帶引數名引數

>>>'今年歲'.format(name = '張三',age = '5')

>>> '張三今年5歲'

python 字串常用方法

python 字串的常用方法 1.len str 字串的長度 2.startswith str 檢視字串是否以str子串開頭,是返回true,否則返回false 3.index str 查詢字串中第一次出現的子串str的下標索引,如果沒找到則報錯 4.find str 查詢從第0個字元開始查詢第一次...

python字串常用方法

string.title python title 方法返回 標題化 的字串,就是說所有單詞都是以大寫開始,其餘字母均為小寫 見 istitle string.upper python upper 方法將字串中的小寫字母轉為大寫字母。string.lower 將字串的大寫字母轉為小寫字母 strin...

python字串常用方法

1,去掉空格和特殊符號 name.strip 去掉空格和換行符 name.strip xx 去掉某個字串 name.lstrip 去掉左邊的空格和換行符 name.rstrip 去掉右邊的空格和換行符 2,字串的搜尋和替換 name.count x 查詢某個字元在字串裡面出現的次數 name.cap...