全能電路設計實戰

2015年8月3日 星期一

Python程式-格式化輸出與字串處理 (三)


格式化輸出 Print: 結構語法基本上同C/C++語言printf


>>> a=4
>>> b=5

>>> print('a=%d'%a)
a=4
>>> print(a,'*',b,'=',a*b)
4 * 5 = 20

一個以上的%d 輸出
>>> print('%d*%d=%d'%(a,b,a*b))
4*5=20

# 多了和C不一樣的功能, 可以用dict的結構,用key找對應的value來輸出
>>> print('%(#2)d*%(#1)d=%(#v)d'%{'#1':a,'#2':b,'#v':a*b})
5*4=20


>>> print('a=%d'%a)
a=4
>>> print('a=%10d'%a)  # 空10格
a=         4
>>> print('a=%010d'%a)  # 空10格且前面補0
a=0000000004

卬浮點數 %f
>>> money=172.85
>>> print('%f',money)
%f 172.85

>>> print('%f'%money)
172.850000

>>> print('$%6.2f''%money)
$172.85

>>> print('$%*.2f'%(10,money)) # 空10格
$         172.85

字串函數


>>> text='it robotic lab'
>>> text.capitalize()
'It robotic lab'
>>> text
'it robotic lab'

>>> text=text.capitalize()  #存回text
>>> text
'It robotic lab'



# Example 1 :判斷是否是整數值 (0-9)

print('input a integer number for N:')
n=input()
while n.isnumeric() == False:
    print('%s is not integer'%n)
    print('input a integer number for N:')
    n=input()

print('%s is integer'%n)

# Example 2 :字串搜尋 find

'''多行字串'''          # ''' 3個單引號

text=''' 針對反課綱學生和民進黨要求立院召開臨時會撤回課綱,國民黨團明將舉行黨團大會凝聚共識。據悉,國民黨仍堅持「立法權不得逾越行政權」底線,傾向不單獨就課綱議題開臨時會,須和政府組改、《就業服務法》及《原住民自治法》等民生議案「綁在一起」處理。民進黨團總召柯建銘昨說,學生與教育部對話無解,召開臨時會是「危機處理」。
黨務高層表示,課綱微調本來就不是議案,屬於行政命令,應回歸到行政院,由教育部和學生們好好坐下來談,看如何解決、妥適處理,否則純粹就課綱議題召開臨時會,不僅有立法權逾越行政權的憲政問題,更恐將變成民進黨的政治舞台,「未來行政院都被立法院把持,台灣是法治國家不能這樣玩。」'''

i=0
total=0
len=len(text)
print (len)
str = input('輸入搜尋字串:')
while i<len:
    i=text.find(str,i)
    if i == -1:
        break
    print(i,text[i])
    total+=1
    i=i+1

print('\n總共找到\"%s\" %d次'%(str,total))

# Example 3 : 分割字串 split


>>> names='hello, world, robotics, lab'
>>> names.split(',')
['hello', 'world', 'robotics', 'lab']
>>> names.split(',')[0]
'hello'
>>> names.split(',')[2]
'robotics'


沒有留言 :

張貼留言