@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 "<stdin>", line 1, in <module>
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),表示去掉首尾的 strtring.lstrip(str),表示只去掉開頭的 strstring.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