close

以下例出字串常用的方法

#把字串都轉成大寫
string='abcde'
string_test=string.upper()
print string_test

#把字串都轉成小寫

string='ABCDEF'

string.lower()

 

string_test='abc:a'
print string_test.split(':')

#用:作分隔,return 一個list回來

['abc', 'a']

a='abc\n   '
x=a.strip() #去除特殊字
print x

abc

in 這個指令,可以檢查字串是否在某個變數裡面

若存在會return True

ex:
print 'B' in string_test 

replace 字串取代

找到的字元or字串,取代成另一個字元or字串

a='abc,b,c,d '
print a
b=a.replace('b','kkkk')
print b

重複輸出字串

str='*'
newstr=str*5
print newstr

取得字串長度

string="abcdef"

string_len=len(string)

print string_len

split function

用split對字串做split 的動作 ,此function 有2個重點  return 一個 list, 分割符號 要用 '' 包起來

 

1.split 分割符號 , 預設為空白

>>> string="a b c d e"
>>> string.split()
['a', 'b', 'c', 'd', 'e']

2.用特定符號做分割

>>> string="a:b:c:d:e"
>>> string.split(":")
['a', 'b', 'c', 'd', 'e']

3.取得分割後的第n個元素

>>> string="a:b:c:d:e"

>>> string.split(':')[0]
'a'

 

 

 

arrow
arrow
    全站熱搜

    yuanann 發表在 痞客邦 留言(0) 人氣()