python笔记:字符串 ## 模版 ``` s=string.Template("This is ${name} big big pig") print s.substitute(name="yzh") ``` ## contains ``` s = "yzh is a big big pig" if "pig" in s: print True if "ppig" not in s: print True ``` ##循环string ``` s = "yzh is a big big pig" for item in s: print item for i,v in enumerate(s): print i,v ``` ## index与substring ``` #从path提取目录名 s = u"D:\个人笔记\书籍" index= s.rfind("\") #也可以用find print s[index+1:] ``` ## 编码解码 编码解码非常的复杂,unicode才能encode,其它的编码可以decode成unicode。 所以在python中,推荐使用unicode(python3默认)。当出现乱码,可以尝试进行解码。 服务器要设置成utf-8,否则,网址访问中文下载路径会找不到。 ```python s= u"hehe"# 这是一个unicode字符串 utf8S = s.encode("utf-8") normalS = utf8S.decode("utf-8") print normalS ``` 在py3中,编码问题大大简化。只有str与byte两种类型。str已经无法看到编码,必须encode成byte才能看到内部结构。 下面是一个py3函数,尝试把字符串转变成可读的编码: ```python3 def readable_or_empty(text): """ 传入参数必须是unicode字符 尝试将b'\xd7\xeeŒ\xc5\xb5\xc4\xcf\xc2\xc2' 之类的字符串转为正常str """ attr = repr(text.encode('raw_unicode_escape')) print(attr) temp_text = "" if u'\\x' in attr and u'\\\\u' not in attr: try: temp_text = text.encode('raw_unicode_escape').decode('gb18030') except: temp_text = "" else: temp_text = text.encode('raw_unicode_escape').decode('utf-8', 'ignore') temp_text = temp_text.encode('utf-8').decode('raw_unicode_escape') return temp_text ``` ## html 安全截断 截断时,确保不会把一个<>给截断 ```python def CutStringSafe(strIn, length): if length > len(strIn): return strIn else: temp_length = length result = strIn[0:length] for i in range(len(result) - 1, -1, -1): if i < len(result) - 8: break char = result[i] if char == '>': break if char == '<': result = result[0:i] return result str_test = "hahadafdsasdf" print("test:", CutStringSafe(str_test,8)) ``` ## 过滤乱七八糟的字符 ``` def only_normal_str(input_str): result = '' for n in re.findall('[\u4e00-\u9fffa-zA-Z 0-9]+', input_str): result += n return result test = 'Swallow' print(only_normal_str(test)) ``` 来自 大脸猫 写于 2016-05-17 14:59 -- 更新于2020-10-19 13:06 -- 2 条评论