Python 三種方法字串轉字典

2021-10-05 01:36:38 字數 1101 閱讀 4312

eval:不安全,容易被使用者惡意操作

ast.literal_eval:安全,專門用於字串型別轉換其他型別

json:只能轉換外單引號,內雙引號的字串

eval和literal_eval

# -

*- coding: utf-8-

*-import json, ast

# todo

: 內單引號,外雙引號

s =",'產品':}"

# todo:外單引號,內雙引號

s_ =

',"產品":}'

print

('s '

,type

(s), s)

print

('s_'

,type

(s_)

, s_)

## 1. eval

res =

eval

(s)print

(type

(res)

, res)

res = ast.

literal_eval

(s)print

(type

(res)

, res)

## 2. literal_eval

res = ast.

literal_eval

(s)print

(type

(res)

, res)

res = ast.

literal_eval

(s_)

print

(type

(res)

, res)

## 3. json

res = json.

loads

(s_)

print

(type

(res)

, res)

s  ,'產品':}

s_ ,"產品":}

, '產品': }

, '產品': }

, '產品': }

, '產品': }

, '產品': }

搜尋字串的三種方法

cpp file fp tfopen szxmlfilepath,l rb if fp null return fseek fp,0,seek end uint nlen ftell fp fseek fp,0,seek set 寬字元型別 wchar t pstr read new wchar t...

NSString字串擷取三種方法

1.定義乙個字串a,擷取a 的某乙個專案組,複製給b,b必須是int型 nsstring a 1.2.30 int b a substringwithrange nsmakerange 4,2 intvalue nslog a n a nslog b d b 解析如下 substringwithra...

左旋字串的三種方法

注 有效次數為 總次數 n 如上圖所示,假設對字串左旋6次和左旋2次,得到的結果是一樣的 思路 include include include include pragma warning disable 4996 遮蔽scanf出現的錯誤 char a abcd1234 變數定義成全域性較好 in...