首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python笔记:字符串

python笔记:字符串

作者头像
超级大猪
发布2019-11-22 09:44:20
4920
发布2019-11-22 09:44:20
举报
文章被收录于专栏:大猪的笔记大猪的笔记

模版

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,否则,网址访问中文下载路径会找不到。

s= u"hehe"# 这是一个unicode字符串
utf8S = s.encode("utf-8")
normalS = utf8S.decode("utf-8")
print normalS

在py3中,编码问题大大简化。只有str与byte两种类型。str已经无法看到编码,必须encode成byte才能看到内部结构。 下面是一个py3函数,尝试把字符串转变成可读的编码:

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 安全截断

截断时,确保不会把一个<>给截断

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 = "haha<hahahaaaaaaa>dafdsasdf"
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 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 模版
  • contains
  • 循环string
  • index与substring
  • 编码解码
  • html 安全截断
  • 过滤乱七八糟的字符
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档