python learning4

字符串方法

#分割
#s.split()將s按照空格(包括多個空格,製表符\t,換行符\n等)分割,並返回所有分割得到的字符串。
line = "1 2 3 4  5"
numbers = line.split()
print numbers
=>
['1', '2', '3', '4', '5']

#s.split(sep)以給定的sep爲分隔符對s進行分割
line = "1,2,3,4,5"
numbers = line.split(',')
print numbers


#連接
#s.join(str_sequence)以s爲連接符將字符串序列str_sequence中的元素連接起來,並返回連接後得到的新字符串:
s = ' '
s.join(numbers)
=>
'1 2 3 4 5'


#替換
#s.replace(part1, part2)將字符串s中指定的部分part1替換成想要的部分part2,並返回新的字符串。
s = "hello world"
s.replace('world', 'python')
=>
'hello python'
#s的值並沒有變化,替換方法只是生成了一個新的字符串

#大小寫轉換
#s.upper()方法返回一個將s中的字母全部大寫的新字符串。
#s.lower()方法返回一個將s中的字母全部小寫的新字符串。

#去除多餘空格
#s.strip()返回一個將s兩端的多餘空格除去的新字符串。
#s.lstrip()返回一個將s開頭的多餘空格除去的新字符串。
#s.rstrip()返回一個將s結尾的多餘空格除去的新字符串。
s = "  hello world   "
s.strip()

#用dir函數查看所有可以使用的方法
dir(s)

#強制轉換爲字符串
#str(ob)強制將ob轉化成字符串
str(1.1 + 2.2)
=>
'3.3'
#repr(ob)也是強制將ob轉化成字符串
repr(1.1 + 2.2)
=>
'3.3000000000000003'

整數與不同進制的字符串的轉化

十六進制:hex(255)
八進制:oct(255)
二進制:bin(255)
int 將字符串轉爲整數:int(‘23’)
按照多少進制來進行轉換,最後返回十進制表達的整數:
int(‘FF’, 16)
int(‘377’, 8)
int(‘11111111’, 2)

格式化字符串

字符串中花括號 {} 的部分會被format傳入的參數替代,傳入的值可以是字符串,也可以是數字或者別的對象

'{} {} {}'.format('a', 'b', 'c')
'{2} {1} {0}'.format('a', 'b', 'c')
'{color} {n} {x}'.format(n=10, x=1.5, color='blue')
=>
'blue 10 1.5'
'{color} {0} {x} {1}'.format(10, 'foo', x = 1.5, color='blue')

from math import pi
'{0:10} {1:10d} {2:10.2f}'.format('foo', 5, 2 * pi)
=>
'foo                 5       6.28'

s = "some numbers:"
x = 1.34
y = 2
# 用百分號隔開,括號括起來
t = "%s %f, %d" % (s, x, y)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章