函数太多,关键词只是相似的这类函数。

引号

Python中三引号可以将复杂的字符串进行复制
Python没有字符类型,有String类型

var1 = 'Hello'
var2="World"

单引号,双引号 都是字符串

str1='hello'    type(str1)=>str
str2='h'        type(str2)=>str
str3='''my'''   type(str3)=>str

为什么设计三引号呢?
转译问题。
比如打印 hello “dear”
python可以

print "hello \"dear\""
print '''hello "dear"''' #左右是三个单引号
print 'hello "dear"'

三个出来的都是 hello “dear”
那么三个双引号呢?双引号里面可以套单引号
三个单引号里面可以套双引号。
三个单引号中间不能套单引号,双引号同。就会产生歧义。
就是单双引号混着用就可以。
三引号有一个特殊的地方:支持字符串跨行:

print '''hello
        world
        aaa'''
=>  hello
    world
    aaa

访问字符串中的字符

s = "hello"
    s[0] =>'h' #第一个
    s[-1]=>'o' #最后一个
    s[-2]=>'l' #最后一个

中括号的被理解成列表,列表里可以存不同类型的元素。这点跟java中的数组不一样。

所以还支持分片操作:
s[0:3] =>hel
s[0:] =>hello
s[0:-1] =>hell
重新给s赋值

s

    =>hello
id(s)
=>1234567   
s='sunyang'
s
=>sunyang
id(s)
=>7654321

注意:python会开辟一块新内存空间保存s,这也和java不一样。
所以要保存原来的s,需要

s2=s

python带引号传入字符串 python输出带引号的字符串_python带引号传入字符串

插入100个*

print '*'*100

python带引号传入字符串 python输出带引号的字符串_字符串_02

s1 = 'hello'
'e' in s1 =>true

print 'hello\n\n'
=>hello
    回车符
    回车符
print r'hello\n'
=> hello\n

print也支持占位符,需要注意的是,连接符和C语言不同,是用%连接的。

print "My name is %s and weight is %d" % ('sunyang',66)
mystr = "hello world abc and abcbank and abc"
print mystr.find('abc')  =>12 返回开始匹配的位置
print mystr.find('abc',13)  =>20

help

可以返回函数的用法

help(mystr.find)返回find方法的用法和参数。[]是可填可不填的参数

python带引号传入字符串 python输出带引号的字符串_python_03

mystr.find('abc',0,20)
len(mystr) =>35

mystr.index(‘abc’)=>12 这个和find一样,但是找一个不存在的字符串时,会抛出异常。但是find不会抛出异常,只会返

print mystr.count('abc') =>3 
print mystr.count('a') =>6

编解码

type(mystr) => str
s2 = mystr.decode(encoding='UTF-8')
type(s2) =>unicode

解码

s3 = mystr.encode(encoding='UTF-8',errors='strict')

errors=’strict’意思是严格检测,解码出错会跑异常,但是可以设置为ignore或replace忽略异常。

replace函数

mystr.replace('abc','cba') =>hello world cba and cbabank and cba

但是mystr本身是没有变化的
除非

mystr = mystr.replace('abc','cba')

则mystr自己也变化了。
选择替换次数,这里是替换2次

mystr.replace('abc','cba',2)

split

mystr.split(" ") 按空格分割
mystr.split(" ",2) 指定分割2个子串,返回的是一个list
mylist = mystr.split(" ") 
mylist .sort() 会按字典排序
----
mystr = "hello world abc and abcbank and abc"
mylist = mystr.split(" ")
mylist.sort()
print mylist
=>['abc', 'abc', 'abcbank', 'and', 'and', 'hello', 'world']


mystr,capitalize() 将字符串首字母大写
mystr.center(70) ,宽度为70个字符,居中,两边补空格

python带引号传入字符串 python输出带引号的字符串_bc_04


检查字符串是否以某为结尾/开头

mystr.endswith("abc") => true
mystr.startswith("abc") => false
mystr.isalnum() #要求至少有一个字符,有数字则为真。

isalpha类的

s1='hello''
s1.isalpha() =>true
s2='hello world'
s2.isalpha() =>false

isdigit()判断全是数字
islower()判断全是小写
isspace()

isjoin类的

s.isjoin(‘xxxx’),在xxxx中插入s中的字符串,s4=hello

python带引号传入字符串 python输出带引号的字符串_字符串_05

s.ljust(width)

python带引号传入字符串 python输出带引号的字符串_字符串_06

同理还有s.rjust();

s.lstrip()去掉左边的空格 同理还有rstrip()

python带引号传入字符串 python输出带引号的字符串_python带引号传入字符串_07

比较重要的是

string.partition('字符串')

将string分为’字符串’左边和右边和’字符串’三部分

python带引号传入字符串 python输出带引号的字符串_python带引号传入字符串_08