python入門:字符串

所有標準序列操作(索引、切片、乘法、成員檢查、長度、最小值、最大值)都適用於字符串,但是字符串是不可變的,因此所有的元素賦值和切片賦值都是非法的。

a = 'http://www.python.org'
a[-3:]='com'
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    a[-3:]='com'
TypeError: 'str' object does not support item assignment

python提供了多種字符串設置方法,以前,主要的解決方法是使用字符串格式設置運算符-百分號。這個運算符的行爲類似C語言中的景點函數printf:在%左邊制定一個字符串,並在右邊指定要設置其格式的值。指定要設置其格式的值,可使用單個值,可使用元組或字典。

format='http:// %s.%s.org'
values= ('www','python')
format % values
'http:// www.python.org'

上述%s稱爲轉換說明符,指出了要將值插入的地方,s意味着將值視爲字符串進行格式設置。如果指定的不是字符串,將使用str將其轉換爲字符串,其他說明符將導致其他轉換形式。

常用的另一種方式

"{},{},and {}".format("first","second","third")
'first,second,and third'
 "{1},{0},{3},{2}".format("first","second","third","four")
'second,first,four,third'
 "{0},{1},{2},{3}".format("first","second","third","four")
'first,second,third,four'
# 調用math中的pi模塊
from math import pi
"{name} is approximately {value:.3f}.".format(value=pi,name="π")     
'π is approximately 3.142.'

這裏value:.3f制定了格式說明符,意味着使用3位小數的浮點數格式。

如果變量與替換字段同名,可使用

from math import e
 f"Euler's constant is roughly {e}."     
"Euler's constant is roughly 2.718281828459045."
同比:
"Euler's constant is roughly {e}.".format(e=e)
"Euler's constant is roughly 2.718281828459045."

設置字符串格式

組成部分:字段名、轉換標誌、格式說明符。

字段名:索引或標識符,指出要設置那個值的格式並使用結果來替換該字段。除指定值外,還可指定值的特定部分,如元素。

轉化標誌:跟在歎號後面的單個字符,當前支持字符包括r(repr)、s(str)、a(ascii)。如果制定了轉換標誌,將不適用對象本身的格式設置機制,而是使用指定的函數將對象轉換爲字符串,在做進一步的格式設置。

格式說明符:跟在冒號後面的表達式,格式說明符讓我們能夠詳細地制定最終的格式,包括格式類型(如字符串,浮點數或十六進制)。

替換字段名

"{} {} {} {}".format(1,2,3,4)						    
'1 2 3 4'
#通過索引來指定那個字段中對應的未命名參數。
"{0} {3} {1} {2}".format(1,2,3,4)     
'1 4 2 3'

基本轉換

print("{pi!s} {pi!r} {pi!a}".format(pi="π"))  
π 'π' '\u03c0'

分別使用str、repr、ascii進行轉換

還可以指定轉換值的類型

 "The number is {}".format(42)	  
'The number is 42'
"The number is {:f}".format(42)   
'The number is 42.000000'

或二進制格式

"The number is {:b}".format(42)	  
'The number is 101010'

字符串格式設置類型說明符

整型:

  •  b 二進制

  • c 字符型,把數字轉成表示unicode的字符

  • d 十進制

  • o 八進制

  • x 十六進制,顯示小寫字母

  • X 十六進制,顯示大寫字母

  • n 與d行爲相同,使用本地的數字表示方式

  • ''(空,沒有空格) 與d相同

浮點數

  • e 科學計數法表示,小寫e

  • E 科學計數法表示,大寫E

  • f 顯示爲定點數,默認小數點後六位

  • F 同f

  • g 自動選擇是否用科學記數法表示

  • G 同g

  • n 同g,使用本地表示方式

  • % 使用百分比表示

  • ''(空) 同g


寬度、精度、和千位符

 "{number:10}".format(number=3)	  
'         3'
"{name:10}".format(name="andy")   
'andy 
 "Pi day is {pi:10.3f}".format(pi=pi)   
'Pi day is      3.142'     '
# 或千位符
"This is {:,}".format(10**10)   
'This is 10,000,000,000'

符號、對齊及填充

 '{:010.2f}'.format(pi)  
'0000003.14'
print('{0:<10.2f}\n{0:>10.2f}\n{0:^10.2f}'.format(pi))   
3.14      
      3.14
   3.14
# 可以制定字符作爲填充字符 
"{:$^15}".format(" hello ")
'$$$$ hello $$$$'

print('{0:10.2f}\n{1:10.2f}'.format(pi,-pi))
     3.14
    -3.14
 
print('{0:10.2f}\n{1:=10.2f}'.format(pi,-pi))
     3.14
-     3.14

print('{0:-.2f}\n{1:-.2f}'.format(pi,-pi))
3.14
-3.14

print('{0:+.2f}\n{1:+.2f}'.format(pi,-pi))
+3.14
-3.14

print('{0:+10.2f}\n{1:+10.2f}'.format(pi,-pi))
    +3.14
    -3.14
   
print('{0: .2f}\n{1: .2f}'.format(pi,-pi))
3.14
-3.14

"{:b}".format(42)
'101010'
"{:#b}".format(42)
'0b101010'
"{:#g}".format(42)
'42.0000'

字符串常用方法

center通過在兩邊添加填充字符(默認爲空格)讓字符串居中
"Hi,How old are you".center(30)
'      Hi,How old are you      '
"Hi,How old are you".center(30,"*")
'******Hi,How old are you******'

find在字符串中查找子串,如果找到,就返回子串的第一個字符的索引,否則返回-1。
"Hi,How old are you".find("old")
7
tmp = "hello,welcome to you"
tmp.find('hi')
-1
還可以指定搜索的起點與終點
tmp.find("hi",0,10)
-1

join用於合併字符串
s = ['1','2','3','4']
s1="+"
s1.join(s)
'1+2+3+4'
dir = '','usr','bin','env'
'/'.join(dir)
'/usr/bin/env'
print('C:' + '\\'.join(dir))
C:\usr\bin\env

lower轉換小寫
'HELLOWORLD'.lower()
'helloworld'

replace替換將指定字符串替換成另一個字符串,並返回替換後結果。

str ="This is a test"
str.replace("is","was")
'Thwas was a test'

split拆分字符串爲序列

 num = '1+2+3+4'
num.split("+")
['1', '2', '3', '4']
'/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']

strip刪除行首與行尾的空白行,並返回刪除後的結果

'   hello world   '.strip()
'hello world'
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章