Python字符串使用方法

Python字符串

有編程基礎的人對字符串並不陌生,在C++中定義一個字符需要帶上數據類型如:

string str=“Hello”

而在Python中定義一個字符串很方便

str = ‘Hello’  #使用單引號

str = “Hello” #使用雙引號

Python字符串使用方法:

capitalize()方法,將字符串首字母大寫

str='hello word!'
test = str.capitalize()
print(test)
輸出:

Hello word!

2 casefold()方法,將字符串轉換爲小寫

str='HELLO word!'
test = str.casefold()
print(test)
輸出:hello word!

3 center(self, width, fillchar=None)方法,使用fillchar填充到原字符串的兩端,直至長度爲width

str='HELLO word!'
test = str.center(12,'a')
print(test)
輸出:HELLO word!a

str='HELLO word!'
test = str.center(13,'a')
print(test)
輸出:aHELLO word!a

4 count(self, sub, start=None, end=None)方法,統計sub在字符串中出現的次數,可以指定起始位置與結束位置

str='abbcccddddeeeee'
test = str.count('c')
print(test)
輸出:3

str='abbcccddddeeeee'
test = str.count('c',0,4)
print(test)
輸出:1

str='abbcccddddeeeee'
test = str.count('ee')
print(test)
輸出:2

5 encode(encoding='UTF-8',errors='strict')方法以 encoding 指定的編碼格式編碼字符串。errors參數可以指定不同的錯誤處理方案。

endswith(self, suffix, start=None, end=None)方法,判斷字符串是否以suffix結尾,可以指定起始位置與結束位置

str='abbcccddddeeeee'
test = str.endswith('e')
print(test)

輸出:TRUE
str='abbcccddddeeeee'
test = str.endswith('e',0,6)
print(test)
輸出:FALSE
str='abbcccddddeeeee'
test = str.endswith('eee')
print(test)
輸出:TRUE
7 expandtabs(self, tabsize=8)方法,將\t轉換爲空格,可指定大小,默認爲8
str='abbccc\tddddeeeee'
test = str.expandtabs(16)
print(test)
輸出:abbccc          ddddeeeee
str='abbccc\tddddeeeee'
test = str.expandtabs()
print(test)
輸出:abbccc  ddddeeeee
8 find(self, sub, start=None, end=None)方法,查找字符串sub第一次出現的位置,若沒有返回-1
str='abbcccddddeeeee'
test = str.find('dd')
print(test)
輸出:6
str='abbcccddddeeeee'
test = str.find('f')
print(test)
輸出:-1
9 format(self, *args, **kwargs)方法,格式化輸出字符串。Python中是這樣說明這個函數的
S.format(*args, **kwargs) -> str
Return a formatted version of S, using substitutions from args and kwargs.The substitutions are identified by braces ('{' and '}').
直譯過來就是返回一個使用參數與kwargs替換後格式化的S,替換被{{}}中的。(英語水平有限,翻譯個大概,各位大神可自行翻譯)
  • 直接替換
str='{0},{1}'
test = str.format('aa','bb')
print(test)
print(str)
輸出:aa,bb
   {0},{1}
  • 指定替換
str='{Name},{age}'
test = str.format(Name='Li',age='18')
print(test)
print(str)
輸出:Li,18
     {Name},{age}
  • 使用列表替換
list = ['a','b',]
list1 = ['c','d',]
str='{0[0]},{1[1]}'
test = str.format(list,list1)
print(test)
輸出:a,d
此測試程序,使用的兩個列表替換str中的值,並使用了數組下標的方式{0[0]}取的是list列表中的第一個元素,{1[1]}取的是列表list1中第二個元素故輸出a,b
  • 格式限定
^、<、>分別是居中、左對齊、右對齊,後面帶寬度,示例如下:
center='{:1^6}'
test = center.format('abc')
print(test)
left='{:2>6}'
test = left.format('abc')
print(test)
right='{:3<6}'
test = right.format('abc')
print(test)
輸出:
1abc11
222abc
abc333
  • 精度與其他類型
b、d、o、x分別是二進制、十進制、八進制、十六進制,示例如下:
str='{:.3f}'
test = str.format(3.1415926)
print(test)
test = '{:b}'.format(20)
print(test)
test = '{:o}'.format(20)
print(test)
test = '{:d}'.format(20)
print(test)
test = '{:x}'.format(20)
print(test)
輸出:
3.142 #不僅保存了後三位還進行了四捨五入
10100 #二進制
24 #八進制
20 #十進制
14 #16進制
  • 使用‘,’號作爲數字的分割
test = '{:,}'.format(2147483647)
print(test)
輸出:
2,147,483,647
10 isalpha(self)方法,判斷字符串中的字符是否爲同一類型,Bool類型
str='adc'
test = str.isalpha()
print(test)
str1='123adc'
test = str1.isalpha()
print(test)
輸出:
True
False
11 isdigit(self)方法,判斷一個字符串中的元素是否均爲數字,Bool類型
str='adc'
test = str.isdigit()
print(test)
str1='1234567890'
test = str1.isdigit()
print(test)
輸出:
False
True
12 islower(self)方法,判斷字符串是否均爲小寫是輸出True,否輸出False
str='adc'
test = str.islower()
print(test)
str1='ABcd'
test = str1.islower()
print(test)
輸出:
True
False
13 isspace(self)方法,判斷字符串是否爲空格是輸出True否輸出False
str='   '
test = str.isspace()
print(test)
str1='  AB   cd  '
test = str1.isspace()
print(test)
輸出:
True
False
14 istitle(self)方法,判斷所有單詞的首字母是否爲大寫是輸出True否輸出False
str='Hello Word'
test = str.istitle()
print(test)
str1='Hello word!'
test = str1.istitle()
print(test)
輸出:
True
False
15 isupper(self)方法,判斷字符串是否均爲大寫
str='HELLO WORD'
test = str.isupper()
print(test)
str1='Hello WORD'
test = str1.isupper()
print(test)
輸出:
True
False
16 join(self, iterable)方法,返回一個連接的字符串
str='*'
test = str.join('hello')
print(test)
輸出:h*e*l*l*o
17 def ljust(self, width, fillchar=' ')方法,左對齊字符並使用fillchar填充至width
str='HELLO'
test = str.ljust(10,'a')
print(test)
輸出:
HELLOaaaaa
18 lower(self)方法,返回一個小寫的字符串
str='HELLO'
test = str.lower()
print(test)
輸出:
hello
19 lstrip(self, chars=None)方法,返回一個從字符串左側開始移除chars的字符串
str='HELLO'
test = str.lstrip('H')
print(test)
輸出:
ELLO
20 partition(self, sep)方法,以sep分割字符串並返回一個包含三個元素的元組
str='hello word'
test = str.partition('o')
print(test)
輸出:
('hell', 'o', ' word')
21 replace(self, old, new, count=-1)方法,使用新的字符串替換舊的字符串默認全部替換,可指定次數
str='hellowordosdsossdo'
test = str.replace('o','TEST',2)
print(test)
輸出:
hellTESTwTESTrdosdsossdo
22 rfind(self, sub, start=None, end=None)方法,返回sub在字符串中最後出現的索引爲找到返回-1,可指定起始與結束位置
str='hello'
test = str.rfind('o')
print(test)
輸出:
4
str='hello'
test = str.rfind('o',0,3)
print(test)
輸出:
-1
23 rindex(self, sub, start=None, end=None)方法,與rfind方法類似,未找到會報ValueErro
str='hello'
test = str.rindex('x')
print(test)
輸出:
ValueError: substring not found
24 rjust(self, width, fillchar=' ')方法,右對齊字符並使用fillchar填充至width
str='hello'
test = str.rjust(8,'T')
print(test)
輸出:
TTThello
25 rpartition(self, sep)方法,以最後一個sep分割字符串並返回一個包含三個元素的元組
str='hello'
test = str.rpartition('l')
print(test)
輸出:
('hel', 'l', 'o')
26 rsplit(self, sep=None, maxsplit=-1)方法,返回一個以sep分片的列表默認是全部分片
str='h-e-l-l-o'
test = str.rsplit('-')
print(test)
輸出:
['h', 'e', 'l', 'l', 'o']
str='h-e-l-l-o'
test = str.rsplit('-',2)
print(test)
輸出:
['h-e-l', 'l', 'o']
27 rstrip(self, chars=None)方法,刪除 string 字符串末尾的指定字符(默認爲空格)
str='h-e-l-l-o'
test = str.rstrip('o')
print(test)
輸出:
h-e-l-l-
28 split(self, sep=None, maxsplit=-1)方法,返回一個以sep分片的列表
str='h-e-l-l-o'
test = str.split('-')
print(test)
輸出:
['h', 'e', 'l', 'l', 'o']
str='h-e-l-l-o'
test = str.split('-',3)
print(test)
輸出:
['h', 'e', 'l', 'l-o']
29 splitlines(self, keepends=False)方法,返回一個以行爲單位的列表默認不包含換行標識
str='hello\nword'
test = str.splitlines()
print(test)
輸出:
['hello', 'word']
str='hello\nword'
test = str.splitlines(True)
print(test)
輸出:
['hello\n', 'word']
30 startswith(self, prefix, start=None, end=None)方法,若該字符串以prefix開頭返回True否則返回False,可以指定開始和結束位置
str='helloword'
test = str.startswith('he')
print(test)
輸出:
True
str='helloword'
test = str.startswith('hel',0,1)
print(test)
輸出:
False
31 strip(self, chars=None)方法,刪除字符串首尾兩端的chars默認爲空格
str='    helloword    '
test = str.strip()
print(test)
輸出:
helloword
str='----helloword----'
test = str.strip('-')
print(test)
輸出:
helloword
32 swapcase(self)方法,將字符串進行大小寫轉換
str='helloword'
test = str.swapcase()
print(test)
print(test.swapcase())
輸出:
HELLOWORD
helloword
33 title(self)將所有單詞的首字母大寫
str='hello word'
test = str.title()
print(test)
輸出:
Hello Word
34 upper(self)方法,將所有單詞大寫
str='hello word'
test = str.upper()
print(test)
輸出:
HELLO WORD
35 zfill(self, width)返回width長度的字符串,左側以0填充
str='hello'
test = str.zfill(10)
print(test)
輸出:
00000hello
耗時三天(每天晚上回來寫點)寫完了Python中字符串的用法,第一次寫博客,受到一位老師的啓發萬事開頭難,堅持!希望能給大家帶來幫助。


發佈了27 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章