python字符串基礎:字符串寫法及常用方法,詳情查看:python官網
python 字符串
1.字符串的三種寫法
單引號 ''(英文下的單引號)In [1]:
'allows embedded "double" quotes'
Out[1]:
'allows embedded "double" quotes'
雙引號 ""(英文下的雙引號)
In [2]:
"allows embedded 'single' quotes"
Out[2]:
"allows embedded 'single' quotes"
三引號 ''' """ (英文下的三引號)
In [3]:
'''Three single quotes''', """Three double quotes"""
Out[3]:
('Three single quotes', 'Three double quotes')
三引號可以寫多行
In [4]:
'''
firt line
second line
third line
......
'''
Out[4]:
'\nfirt line\nsecond line\nthird line\n......\n'
字符串內可放置的內容
In [5]:
'g#o~o*d, 你\\好-w+hy.32?'
Out[5]:
'g#o~o*d, 你\\好-w+hy.32?'
2. 字符串方法 String Methods
字符串支持所有常規的序列操作以及下面的方法:
str.capitalize() 首字母大寫In [6]:
str = 'good luck'
In [7]:
str.capitalize()
Out[7]:
'Good luck'
str.count(sub,start,end) 字符串計數
In [8]:
str.count('o',2,5) # 對'o'在str中的第2個到第4個字母進行計數
Out[8]:
1
str.expandtabs(tabsize=8) tab擴展,擴大或縮小tab(默認是8)
In [9]:
'01\t012\t0123\t01234'.expandtabs(3)
Out[9]:
'01 012 0123 01234'
str.find(sub,start,end) 找到某個字符的位置,返回sub在索引中的最小位置
In [10]:
str.find('o',2,4)
Out[10]:
2
str.format(*args, **kwargs) 字符串格式化 注意位置與關鍵字要對應
In [11]:
print (str + ' {}!'.format('boy'))
good luck boy!
In [12]:
'大家跟{0}一起學{1} {2} ~'.format('我', 'Python', 8)
Out[12]:
'大家跟我一起學Python 8 ~'
str.join(iterable) 向字符串中插入字符串
In [13]:
str.join('XXX')
Out[13]:
'Xgood luckXgood luckX'
str.ljust(width, fillcha) 左對填充指定寬度字符串
In [14]:
str.ljust(20,'!')
Out[14]:
'good luck!!!!!!!!!!!'
str.lower() 小寫轉換
In [15]:
str.lower()
Out[15]:
'good luck'
str.lstrip(chars) 從左邊截取包含指定集的字符合並返回截取後的字符串
In [16]:
str.lstrip('god c') # 從左邊開始截取包含'godc'的字符串
Out[16]:
'luck'
str.partition(sep) 將字符串按第一個分隔符截成包含三個字符串的元組
In [17]:
str.partition(' ')
Out[17]:
('good', ' ', 'luck')
str.replace(old, new, count) 字符串替換
In [18]:
str.replace('o', '~', 2)
Out[18]:
'g~~d luck'
str.split(sep = None, maxsplit = -1) 拆分字符串為列表 maxsplit+1為拆分為列表中元素的個數,不指定或者指定為-1時,不會限制拆分的元素個數,指定時則拆分為指定的個數
In [19]:
str.split()
Out[19]:
['good', 'luck']
str.splitlines(keepends) 按照分隔符將元素輸出為一個列表
In [20]:
(str + '\n' + str).splitlines()
Out[20]:
['good luck', 'good luck']
str.strip(chars) 去掉字符串前後的包含指定集合的字符
In [21]:
str.strip('go')
Out[21]:
'd luck'
str.upper() 轉換為大寫
In [22]:
str.upper()
Out[22]:
'GOOD LUCK'
str.zfill() 用0從向右填充到指定寬度
In [23]:
str.zfill(20)
Out[23]:
'00000000000good luck'