python字符串操作
C:>python --version
Python 3.4.0
C:>python
Python 3.4.0 (v3.4.0:04f714765c13, Mar 16 2014, 19:24:06) [MSC v.1600 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
生成字符串
str="welcome to python 3.4.0 string world!"
打印字符串
print(str)
welcome to python 3.4.0 string world!
字符串长度获取
len(str)
37
链接字符串
str2='George.'
str += str2
str
'welcome to python 3.4.0 string world!George.'
复制字符串
str2
'George.'
str2=str
str2
'welcome to python 3.4.0 string world!George.'
比较字符串
str
'welcome to python 3.4.0 string world!George.'
str2
'welcome to python 3.4.0 string world!George.'import operator
operator.eq(str,str2)
True
str==str2
True
截取字符串
str
'welcome to python 3.4.0 string world!George.'
str[2:]
'lcome to python 3.4.0 string world!George.'
str[2:30]
'lcome to python 3.4.0 string'
注意点:下标从0开始,str[2:30]不包含下标为20 的字符。
str[:30]
'welcome to python 3.4.0 string'
str[-1]
'.'
str[::-1]
'.egroeG!dlrow gnirts 0.4.3 nohtyp ot emoclew'
str
'welcome to python 3.4.0 string world!George.'str[-5:-3]
'or'
str[2]
'l'
字符串中的搜索与替换
str
'welcome to python 3.4.0 string world!George.'
str.find('3.4.0')
18
str.find('3.4.0',0,37)
18
str.find('3.5.0')
-1
str.index('3.5.0')
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found
str
'welcome to python 3.4.0 string world!George.'
str.count('o')
5
字符串的分割与组合
str=str.split('!')
str
['welcome to python 3.4.0 string world', 'George.']
str=str[0] +'! ' + str[1]
str
'welcome to python 3.4.0 string world! George.'
比较两个字符串是否一致
str
str += str2
>>> str
'welcome to python 3.4.0 string world!George.'
复制字符串
>>> str2
'George.'
>>> str2=str
>>> str2
'welcome to python 3.4.0 string world!George.'
比较字符串
>>> str
'welcome to python 3.4.0 string world!George.'
>>> str2
'welcome to python 3.4.0 string world!George.'
>>>
>>> import operator
>>> operator.eq(str,str2)
True
>>> str==str2
True
截取字符串
>>> str
'welcome to python 3.4.0 string world!George.'
>>> str[2:]
'lcome to python 3.4.0 string world!George.'
>>> str[2:30]
'lcome to python 3.4.0 string'
注意点:下标从0开始,str[2:30]不包含下标为20 的字符。
>>> str[:30]
'welcome to python 3.4.0 string'
>>> str[-1]
'.'
>>> str[::-1]
'.egroeG!dlrow gnirts 0.4.3 nohtyp ot emoclew'
>>> str
'welcome to python 3.4.0 string world!George.'
>>>
>>>
>>> str[-5:-3]
'or'
>>> str[2]
'l'
字符串中的搜索与替换
>>> str
'welcome to python 3.4.0 string world!George.'
>>> str.find('3.4.0')
18
>>> str.find('3.4.0',0,37)
18
>>> str.find('3.5.0')
-1
>>> str.index('3.5.0')
Traceback (most recent call last):
File "", line 1, in
ValueError: substring not found
>>> str
'welcome to python 3.4.0 string world!George.'
>>> str.count('o')
5
字符串的分割与组合
>>> str=str.split('!')
>>> str
['welcome to python 3.4.0 string world', 'George.']
>>> str=str[0] +'! ' + str[1]
>>> str
'welcome to python 3.4.0 string world! George.'
>>>
比较两个字符串是否一致
>>> str
'welcome to python 3.4.0 string world! George.'
str2
'welcome to python 3.4.0 string world!George.'
import operator
operator.eq(str,str2)
False