python字符串

python 的字符串可以通过 a[n] 的方式定位到字符串中的某个字符

但是不能通过这种方式改变字符串的值

php也能够通过a[n]定位某个字符,不同的是,php也可以通过这种方式改变字符串的值, js的行为和python一致

下面介绍python字符串的一些常用的方法

1. find 

>>> x = 'abcdefg'
>>> x.find('cde')
2
>>> x.find('cdf')
-1
>>> 

返回字符串所在位置的最左端的索引。如果没有找到则返回-1

类似于php中的strpos,但是Php如果没有找到则返回0

js 的indexOf和python的find行为一致

2.join

链接字符串

['1', '2', '3'] ('1', '2', '3') 可以进行链接 [1, 2, 3]因为不是字符而不能连接

>>> x = ('a', 'b', 'c')
>>> '/'.join(x)
'a/b/c'
>>> x = ['a', 'b', 'c']
>>> '/'.join(x)
'a/b/c'
>>> 

 

类似于php的implode('', $arr)

js的join()参数可选,默认为逗号

var t = ['a', 'b', 'c'];

t.join();

输出a,b,c

3. lower

'ABC'.lower()

'abc'.upper()

>>> 'ABC'.lower();
'abc'
>>> 'abc'.upper()
'ABC'
>>> 'hello world'.title()
'Hello World'
>>> 

 

php: strtolower()  strtoupper()

js: str.toLowerCase()  str.toUpperCase()

 

4.replace

>>> 'this is a test'.replace('is', 'eez')
'theez eez a test'
>>> 

 

php: str_replace

js: str.replace()

 

5.split

将字符串分隔成序列

str = '1+2+3+4'

str.split('+')

['1', '2', '3', '4']

>>> '/usr/bin/env'.split('/')
['', 'usr', 'bin', 'env']
>>> 

 

>>> 'using the default'.split();
['using', 'the', 'default']
>>> 

 

如果不提供任何分隔符,程序会把空格、指标、换行符作为分隔符

php: explode

js: str.split() 

 

6.strip

返回去除两侧空格的字符串

lstrip 左侧的 rstrip 右侧的

可以指定要去除的字符

>>> ' a '.strip()
'a'
>>> ' a '.lstrip()
'a '
>>> '*a*'.lstrip('*')
'a*'
>>> 

 

php : trim ltrim rtrim

js: js没有提供trim jquery提供了$.trim()

 

posted @ 2015-05-20 18:37  小刘_php  阅读(104)  评论(0)    收藏  举报