python之字符串及其操作
2018-10-29 本文已影响0人
谢小磊
Character字符型:
- Character字符型:字符型数据代表了所有可以定义的字符
- 定义方式:使用单引号(' ')或双引号(" ")括起来
- 运算规则:无
#字符串str用单引号(' ')或双引号(" ")括起来
x = '我是一个字符串';
y = "我也是一个字符串";
#使用反斜杠(\)转义特殊字符。
s = 'Yes,he doesn\'t'
print(s, type(s), len(s))
#Yes,he doesn't <class 'str'> 14
#如果你不想让反斜杠发生转义,
#可以在字符串前面添加一个r,表示原始字符串
print('C:\some\name')
print(r'C:\some\name')
#C:\some
#ame
#C:\some\name
#分析:\n为特殊字符(回车符)。
#反斜杠可以作为续行符,表示下一行是上一行的延续。
#还可以使用"""..."""或者'''...'''跨越多行
s = "abcd\
efg"
print(s);
s = """
Hello I am fine!
Thinks.
"""
print(s);
#abcdefg
#Hello I am fine!
#Thinks.
#字符串可以使用 + 运算符串连接在一起,或者用 * 运算符重复:
print('str'+'ing', 'you'*3)
#string youyouyou
#Python中的字符串有两种索引方式
#第一种是从左往右,从0开始依次增加
#第二种是从右往左,从-1开始依次减少
#注意,没有单独的字符类型,一个字符就是长度为1的字符串
word = 'Python'
print(word[0], word[5])
print(word[-1], word[-6])
#P n
#n P
#还可以对字符串进行切片,获取一段子串
#用冒号分隔两个索引,形式为变量[头下标:尾下标]
#截取的范围是前闭后开的,并且两个索引都可以省略
word = 'ilovepython'
word[1:5]
#'love'
word[:]
#'ilovepython'
word[5:]
#'python'
word[-10:-6]
#'love'
#Python字符串不能被改变
#向一个索引位置赋值,比如word[0] = 'm'会导致错误。(字符串不允许被更改)
word[0] = 'm'
#检测开头和结尾
filename = 'spam.txt'
filename.endswith('.txt')
#True
filename.startswith('file:')
#False
url = 'http://www.python.org'
url.startswith('http:')
#True
choices = ('http:', 'https')
url = 'https://www.python.org'
url.startswith(choices)
#True
#查找某个字符串
string = "I am King"
string.find("am")
string.find("boy")
#2
#-1
#分析:2即表示所找字符串位的位置,-1即查询字符串没有找到需要的字符串。
#结果大于0,即所查字符串存在。反之,不存在。
#忽略大小写的搜索
import re
text = 'UPPER PYTHON, lower python, Mixed Python'
re.findall('python', text, flags=re.IGNORECASE)
#['PYTHON', 'python', 'Python']
#搜索和替换
text = 'yeah, but no, but yeah, but no, but yeah'
text.replace('yeah', 'yep')
#'yep, but no, but yep, but no, but yep'
#忽略大小写的替换
text = 'UPPER PYTHON, lower python, Mixed Python'
re.sub('python', 'snake', text, flags=re.IGNORECASE)
#'UPPER snake, lower snake, Mixed snake'
#合并拼接字符串
parts = ['Is', 'Chicago', 'Not', 'Chicago?']
' '.join(parts)
#'Is Chicago Not Chicago?'
','.join(parts)
#'Is,Chicago,Not,Chicago?'
''.join(parts)
#'IsChicagoNotChicago?'
你的关注和点赞,会是我无限的动力,谢谢。