1.字符串的定义:
# 字符串定义的第一种方式:
>>> str1 = 'our company is westos'
# 字符串定义的第二种方式:
>>> str2 = "our company is westos"
# 字符串定义的第三种方式:
>>> str3 = """our company iswestos"""
2.字符串的操作:
(1)字符串索引:
定义一个字符串 a ='amazing'
字符串的索引是从字符串的第一个字符定义为 【0】位置 开始进行索引
>>> a = 'amazing'
>>> type(a)
<type 'str'>
>>> a[0]
'a'
>>> a[1]
'm'
>>> a[3]
'a'
>>> a[0]+a[1]
'am'
>>> a[0]+a[2]
'aa'
(2)字符串切片:
定义一个字符串 a ='amazing'
字符串切片的分隔符是 ‘:’ 并且用‘ [] ’ 框起来
示例 : a[x:x:x]
>>> a
'amazing'
>>> a[1:5:2]
'mzi'
>>> a[1:5] //代表切片取出第2个到第4个
'mazi'
>>> a[4:]
'ing'
>>> a[4:1] //python中默认是从左向右取值
''
>>> a[4:1:-1] //当步长为-1时,从右向左取值
'gni'
>>> a[:]
'amazing'
>>> a[-1]
'g'
>>> a[-4:-1] //代表倒数第2个到倒数第4个切片
'niz'
3.操作方法的用法帮助:
使用 help(s.xxxxx)来查看
In [2]: s = 'myworld'
In [7]: help(s.center)
Help on built-in function center:
center(...)
S.center(width[, fillchar]) ->string
Return S centered in a string oflength width. Padding is
done using the specified fillcharacter (default is a space)
In [8]: s.center(30,'@')
Out[8]: '@@@@@@@@@@@myworld@@@@@@@@@@@@'
In [9]: s.center(20)
Out[9]: ' myworld '
部分函数用法:
(1) s.center() 增添s输出长度
(2) s.isalpha() 判断s是否为字母
(3) s.isalnum() 判断s是否为字母或者数字
(4) s.isdigit() 判断s是否为数字
示例:
[kiosk@foundation44 Desktop]$ python
Python 2.7.5 (default, Oct 11 2015, 17:47:16)
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or"license" for more information.
>>> s = 'ohmygod'
>>> s[2]+s[3]+s[4]
'myg'
>>> s[2:5]
'myg'
>>> s[:5]
'ohmyg'
>>> s[2:]
'mygod'
>>> s[0:3:2] ##输出
'om'
>>>
[kiosk@foundation44 Desktop]$ ipython
In [2]: s = 'hello'
In [3]: s.capitalize()
Out[3]: 'Hello'
In [6]: help(s.center)
In [7]: s.center
Out[7]: <function center>
In [10]: s.center(11,'k')
Out[10]: 'kkkhellokkk'
In [13]: "he".isupper()
Out[13]: False
In [14]: "he".isalnum()
Out[14]: True
In [15]: "he".isalpha()
Out[15]: True
In [16]: "he2".isalpha()
Out[16]: False
In [17]: "he2".isalnum()
Out[17]: True
In [19]: "he2".isdigit()
Out[19]: False
In [20]: "he".isdigit()
Out[20]: False
In [21]: "2".isdigit()
Out[21]: True