一、字符串的创建
有三种形式:单引号('A')、双引号("A")、三引号(''' A'''),举例如下:
>>> s='hello world'
>>> print(s)
hello world
>>> ss="hello world"
>>> print(ss)
hello world
>>> sss='''hello world'''
>>> print(sss)
hello world
一种错误形式("'A'"),如下:
>>> sss="'hello world'"
>>> print(sss)
'hello world'
另外,需注意,字符串一旦声明,无法更改:
>>> s='hello world'
>>> s[0]
'h'
>>> s[0]='k'
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
s[0]='k'
TypeError: 'str' object does not support item assignment
二、字符串常用的判断语句
1.判断一个字符串是否在已有字符串中,有两种方法:in、not in,举例如下:
>>> s='hello world'
>>> 'h' in s
True
>>> 'w' not in s
False
2.判断两个字符串是否相等,用is,如下:
>>> 'hello ' is 'hello'
False
>>> s="hello"
>>> ss='hello'
>>> s is ss
True
3.判断字符串结尾字符,endswith()
>>> s='hello'
>>> s.endswith('d') ##注意:endswith()为字符串s的一个属性,所以格式为s.endswith(),另外,括号里是字符串的形式,必须用‘’
False
>>> s.endswith('o')
True
4.判断字符串是否只包含字母和数字,没有别的类型,isalnum()
>>> ss='hello123'
>>> ss.isalnum()
True
>>> sss='hello '
>>> sss.isalnum()
False
>>> s='h'
>>> s.isalnum()
True
>>> ssss='hello123+'
>>> ssss.isalnum()
False
>>> sssss='123'
>>> sssss.isalnum()
True
5.判断字符串是否只包含字母,isalpha();是否只包含数字,isdigit()
>>> s.isalpha() #借用上小节例子
True
>>> ss.isalpha()
False
>>> sss.isalpha()
False
>>> s.isdigit()
False
>>> ss.isdigit()
False
>>> sssss.isdigit()
True
三、字符串取值方法
1.通过字符串元素下标取值,值得注意的是,下标为左闭右开,即不包含最后边元素。
>>>s="hello world"
>>>s[0:3] #取前三个元素
'hel'
>>> s[-5:-3]
'wo'
>>> s[1:]
'ello world'
>>> s[0:-1]
'hello worl'
2.for循环,依次取出字符串里面的元素
1)循环字符串对象
s='hello world'
for i in s[0:4]:
print(i)
##结果如下:
>>>
h
e
l
l
2)循环字符串长度,从字符串0位置开始,依次打印
s='hello world'
for i in range(len(s)-6): #若是len(s),则依次打印整个字符串
print(s[i]) #注意[],而不是()
##结果如下:
>>>
h
e
l
l
o
四、去掉字符串两边的空格
>>> s=' hello world '
>>> s.lstrip() #去掉左边空格
'hello world '
>>> s.rstrip() #去掉右边空格
' hello world'
>>> s.strip() #去掉两边空格,但中间的空格去不掉
'hello world'
切记,strip()只是处理字符串首尾字符,默认为空格。
>>> s.strip('d')
' hello world '
>>> ss='hello world'
>>> ss.strip('d')
'hello worl'