@Author :Runsen
Python字串總結
什麼字串
字串是由獨立字元組成的一個序列,通常包含在單引號(‘ ’),雙引號(”“)
三引號(‘’‘ ’‘’)
s1 = ‘hello’
s2 = “hello”
s3 = “”“hello”“”
s1 == s2 == s3
True
三引號字串常用於函式的註釋
def calculate_similarity(item1, item2):
“”“
Calculate similarity between two items
Args:
item1: 1st item
item2: 2nd item
Returns:
similarity score between item1 and item2
”“”
跳脫字元
用 \ 開頭的字串,來表示一些特定意義的字元
s = ‘a\nb\tc’
print(s)
a
b c
len(s)
5
程式碼中的‘\n’,表示一個字元——換行符;‘\t’也表示一個字元,四個空格
字元 a,換行,字元 b,然後製表符,最後列印字元 c 最後列印的輸出橫跨了兩行,但是整個字串 s 仍然只有 5
常用操作
name = ‘jason’
name[0]
‘j’
name[1:3]
‘as’
for char in name:
print(char)
j
a
s
o
n
注意python的字串是不可變的
s = ‘hello’
s[0] = ‘H’
Traceback (most recent call last):
File “
TypeError: ‘str’ object does not support item assignment
只能透過船建立新的字串
s = ‘H’ + s[1:]
s = s。replace(‘h’, ‘H’)
在java 中有可變的字串,StringBuilder ,每次改變字串,無需建立新的字串,時間複雜度為O(1)
但是在python中如果想要改變字串,往往需要O(n)的時間複雜度,n是新字串的長度
拼接字串
str1 += str2 # 表示 str1 = str1 + str2
# 這個時間複雜度是多少
s = ‘’
for n in range(0, 100000):
s += str(n)
在python2中總的時間複雜度就為 O(1) + O(2) + … + O(n) = O(n^2)
但是在python3中 str1 += str2 首先會檢測str1 是否有其他的引用
所以在python3中時間複雜度是O(n)
l = []
for n in range(0, 100000):
l。append(str(n))
l = ‘ ’。join(l)
由於列表的 append 操作是 O(1) 複雜度,時間複雜度為 n*O(1)=O(n)。
split分割
def query_data(namespace, table):
“”“
given namespace and table, query database to get corresponding
data
”“”
path = ‘hive://ads/training_table’
namespace = path。split(‘//’)[1]。split(‘/’)[0] # 返回‘ads’
table = path。split(‘//’)[1]。split(‘/’)[1] # 返回 ‘training_table’
data = query_data(namespace, table)
string。strip(str),表示去掉首尾的 str
tring。lstrip(str),表示只去掉開頭的 str
string。rstrip(str),表示只去掉尾部的 str
在讀入檔案時候,如果開頭和結尾都含有空字元,就採用strip函式
s = ‘ my name is jason ’
s。strip()
‘my name is jason’
格式化
format
print(‘no data available for person with id: {}, name: {}’。format(id, name))
%
print(‘no data available for person with id: %s, name: %s’ % (id, name))
%s 表示字串型,%d 表示整型
兩種字串拼接操作,哪個更好
s = ‘’
for n in range(0, 100000):
s += str(n)
l = []
for n in range(0, 100000):
l。append(str(n))
s = ‘ ’。join(l)
# 第一個 +=
import time
start_time =time。perf_counter()
s = ‘’
for n in range(0,1000000):
s += str(n)
end_time = time。perf_counter()
# 5。7604558070000005
print(end_time - start_time)
# 第二個 join
import time
start_time =time。perf_counter()
s = []
for n in range(0,1000000):
s。append(str(n))
‘’。join(s)
end_time = time。perf_counter()
# 0。622547053
print(end_time - start_time)
# 第三個 map
import time
start_time = time。perf_counter()
s = ‘’。join(map(str, range(0, 1000000)))
end_time = time。perf_counter()
# 0。403433529
print(end_time - start_time)
對於資料量大的map好過join,join好過 +=
對於資料量小的map 好過 += 好過join