1. 程式人生 > >python_11(format、轉義字元、連線字元、字串操作函式、字串反轉)

python_11(format、轉義字元、連線字元、字串操作函式、字串反轉)

——————–資料格式化—————————-

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 格式化字串
str1 = "version"
num = 1.0
format = "%s" % str1
print format
format = "%s %d" % (str1, num)
print format

# 帶精度的格式化
print "浮點型數字: %f" % 1.25   
print "浮點型數字: %.1f" % 1.25 
print "浮點型數字: %.2f" % 1.254 

# 使用字典格式化字串
print "%(version)s: %(num).1f"
% {"version": "version", "num": 2} # 字串對齊 word = "version3.0" print word.center(20) print word.center(20, "*") print word.ljust(0) print word.rjust(20) print "%30s" % word #輸出 >>> version version 1 浮點型數字: 1.250000 浮點型數字: 1.2 浮點型數字: 1.25 version: 2.0 version3.0 *****version3.0***** version3.0
version3.0 version3.0 >>>

——————-轉義字元———————

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 輸出轉義字元
path = "hello\tworld\n"
print path
print len(path)  
path = r"hello\tworld\n" 
print path
print len(path)  


# strip()去掉轉義字元
word = "\thello world\n"
print "直接輸出:"
, word print "strip()後輸出:", word.strip() print "lstrip()後輸出:", word.lstrip() print "rstrip()後輸出:", word.rstrip() #輸出 >>> hello world 12 hello\tworld\n 14 直接輸出: hello world strip()後輸出: hello world lstrip()後輸出: hello world rstrip()後輸出: hello world >>>

—————–連線字元—————————

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 使用"+"連線字串
str1 = "hello "
str2 = "world "
str3 = "hello "
str4 = "China "
result = str1 + str2 + str3
result += str4
print result

# 使用join()連線字串
strs = ["hello ", "world ", "hello ", "China "]
result = "".join(strs)
print result

# 使用reduce()連線字串
import operator
strs = ["hello ", "world ", "hello ", "China "]
result = reduce(operator.add, strs, "")
print result

#輸出
>>> 
hello world hello China 
hello world hello China 
hello world hello China 
>>> 

——————字串操作函式———————–

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 使用索引擷取子串
word = "world"
print word[4]

# 使用split()獲取子串
sentence = "Bob said: 1, 2, 3, 4"
print "使用空格取子串:", sentence.split()
print "使用逗號取子串:", sentence.split(",")
print "使用兩個逗號取子串:", sentence.split(",", 2)

# 字串連線後將分配新的空間
str1 = "a"
print id(str1)
print id(str1 + "b")

# 特殊切片擷取子串
str1 = "hello world"
print word[0:3]
print str1[::2]
print str1[1::2]


#輸出
>>> 
d
使用空格取子串: ['Bob', 'said:', '1,', '2,', '3,', '4']
使用逗號取子串: ['Bob said: 1', ' 2', ' 3', ' 4']
使用兩個逗號取子串: ['Bob said: 1', ' 2', ' 3, 4']
41185408
46365832
wor
hlowrd
el ol
>>> 
startswith()函式判斷文字是否以某個字元開始,
endswith()函式判斷文字是否以某個字元結束。

—————–字串反轉————————-

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 使用list的reverse()
def reverse(s):    
    li = list(s) 
    li.reverse()
    s = "".join(li)
    return s

print reverse("hello")

# 迴圈輸出反轉的字串
def reverse(s):
    out = ""
    li = list(s) 
    for i in range(len(li), 0, -1):
        out += "".join(li[i-1])
    return out

print reverse("hello")

# 特殊切片反轉字串
def reverse(s):
    return s[::-1]

print reverse("hello")

#輸出
>>> 
olleh
olleh
olleh
>>>