深入淺出字符串

注:Python 的字符串是不可變的(immutable)

使用場景:
日志的打印、程序中函數(shù)的注釋、數(shù)據(jù)庫的訪問、變量的基本操作

寫法:

  • 單引號(''),如 name = 'zhangsan'
  • 雙引號(""),如 gender = "male"
  • 三引號之中(''' '''或 """ """):主要應用于多行字符串的情境,比如函數(shù)的注釋
def calculate_similarity(item1, item2):
    """
    Calculate similarity between two items
    Args:
        item1: 1st item
        item2: 2nd item
    Returns:
      similarity score between item1 and item2
    """



轉義字符:
用反斜杠開頭的字符串,來表示一些特定意義的字符

轉義字符.png

字符串的拼接方法:

  • 加號:str1 += str2
  • 內置函數(shù) json:
l = []
for n in range(0, 100000):
    l.append(str(n))
l = ' '.join(l)
print(l)


字符串的分割方法:string.split(separator)
場景:常常應用于對數(shù)據(jù)的解析處理,比如我們讀取了某個文件的路徑,想想要調用數(shù)據(jù)庫的 API,去讀取對應的數(shù)據(jù)

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表示需要去除空格的字符串
  • 前空格:lstrip
  • 尾空格:rstrip



字符串的查找方法:
string.find(sub, start, end):表示從 start 到 end 查找字符串中子字符串 sub的位置



字符串的格式化:
場景:通常會用在程序的輸出、logging
比如我們有一個任務,給定一個用戶的 userid,要去數(shù)據(jù)庫中查詢該用戶的一些信息,并返回。而如果數(shù)據(jù)庫中沒有此人的信息,我們通常會記錄下來,這樣有利于往后的日志分析,或者是線上bug 的調試

  • string.format()
    注:大括號{}就是所謂的格式符,用來為后面的真實值——變量 name 預留位置。
id = '123'
name='zhangsan'
print('no data available for person with id:{}, name:{}'.format(id, name))
  • f-string(Python3.6引入):以 f 或 F 修飾符引領的字符串(f'xxx' 或 F'xxx'),以大括號 {} 標明被替換的字段;在本質上并不是字符串常量,而是一個在運行時運算求值的表達式
    官方解釋:While other string literals always have a constant value, formatted strings are really expressions evaluated at run time.
print(f'no data available for person with id:{id}, name:{name}')



思考題:
下面的兩個字符串拼接操作,你覺得哪個更優(yōu)呢?
A:

s = ''
for n in range(0, 1000000):
    s += str(n)

B:

l = []
for n in range(0, 1000000):
    l.append(str(n))
    
s = ' '.join(l)

C:

s = ''.join(map(str, range(0, 1000000)))

D:

s = ''.join([str[i] for i in range(0, 1000000)])

代碼解答:

import time

# A
start_time1 = time.perf_counter()
s1 = ''
for n in range(0, 1000000):
    s1 += str(n)
end_time1 = time.perf_counter()
print(f'time elapse1: {end_time1 - start_time1}')

# B
start_time2 =time.perf_counter()
s2 = []
for n in range(0, 1000000):
    s2.append(str(n))
end_time2 = time.perf_counter()
print(f'time elapse2: {end_time2 - start_time2}')

# C
start_time3 = time.perf_counter()
s3 = ''.join(map(str, range(0, 1000000)))
end_time3 = time.perf_counter()
print(f'time elapse3: {end_time3 - start_time3}')

# D
start_time4 = time.perf_counter()
l = [str(i) for i in range(0, 1000000)]
s4 = ''.join(l)
end_time4 = time.perf_counter()
print(f'time elapse4: {end_time4 - start_time4}')

輸出時間:

time elapse1: 2.5405207
time elapse2: 0.38024557800000025
time elapse3: 0.256282659
time elapse4: 0.28742126300000015

補充說明:數(shù)據(jù)越大,方案C越高效,效果更明顯
由此可見,join map 具有最好的性能,列表生成器 + join 次之, append + join慢一些,+=最慢

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容