python基础-字符串

  1. 字符串的类型

如何判断是不是json串?

能实现dump的功能,就是json

如果不能实现load和dump,就不是json串

>>> import json

>>> d={"1":"a"}

>>> json.dumps(d)

'{"1": "a"}'

>>> json.loads(json.dumps(d))

{u'1': u'a'}

 

新思路:可以通过判断某些特征来判定是不是要的类型。

 

 

 

 

 

 

 

 

 

 

Strip()清空所有不可见字符

 

但是不能去掉中间的。

 

 

 

>>> "   abc  ".lstrip()
'abc  '
>>> "   abc  ".rstrip()
'   abc'
>>> "*   abc  *".rstrip("*")
'*   abc  '
>>> "*   abc  *".lstrip("*")
'   abc  *'

 

  大小写互换

 

 

 

 

 

 

 

 

 

 

 

小题练习:

查找一句话中有几个boy

#encoding=utf-8

 

sum=0

start_pos=0

s="boy,he is a boy"

while(1):

    if s.find("boy",start_pos)!=-1:

        start_pos=s.find("boy",start_pos)+1   #从找到的位置加1继续往后找

        sum+=1

    else:

        break

 

print sum

 

 

 

 

 

 

 

 

 

rfind 表示从后面开始查找

 

replace

 

expandtabs

 

split()

 

 

splitlines()

 

 

rsplit()

 

 

join()

 

 

in+not in+ startswith+endwith

 

 

isalpha()+isalnum()不区分大小写

 

 

isdigit()

 

 

isspacee()

 

 

Isupper()+islower() 判断大小写

 

 

istitle()

 

 

maketrans()

 

 

import string
t=string.maketrans('abc','ABC')
print 'abc123'.translate(t,'123')

 

ord+chr+unichr

 

 

数字型与字符串类型转换

#coding=utf-8

import string

s = "18"

#数字型字符串转十进制整数

d = string.atoi(s)

print d

#转八进制

o = string.atoi('011', 8)

print o

#转十六进制

h = string.atoi('0x11', 16)

print h

 

 

Count()统计字符出现次数

posted @ 2018-03-21 22:45  小七Libra  阅读(132)  评论(0)    收藏  举报