python字符串的特性及相关应用

一.字符串定义

字符串是 Python 中最常用的数据类型。用单引号(' '),双引号(" ")或者三引号(''' ''')括起来的数据称为字符串(其中,使用三引号的字符串可以横跨多行

创建字符串很简单,只要为变量分配一个值即可。例如:

str1 = 'Hello World'

str2 = "Hello World"

str3 = """Hello World"""

二.转义字符

在需要在字符中使用特殊字符时,python用反斜杠(\)转义字符。如下表:

转义字符描述
\(在行尾时)续行符
\\反斜杠符号
\'单引号
\"双引号
\a响铃
\b退格(Backspace)
\e转义
\000
\n换行
\v纵向制表符
\t横向制表符
\r回车
\f换页
\oyy八进制数yy代表的字符,例如:\o12代表换行
\xyy十进制数yy代表的字符,例如:\x0a代表换行
\other其它的字符以普通格式输出

三.字符串特性

字符串是字符的有序集合,可以通过其位置来获得具体的元素。在python中,字符串中的字符是通过索引来提取的,索引从0开始。

字符串可以取负值,表示从末尾提取,最后一个为-1,倒数第二个为-2,即程序认为可以从结束处反向计数。

1.索引

索引即获取特定偏移的元素

例: s = "hello"

##正向索引
>>> s[1]
'e'
>>> s[0]
'h'
>>> s[4]
'o'

##反向索引
>>> s = "hello world"
>>> s[-1]
'd'
>>> s[-2]
'l'
>>> s[-3]
'r'

2.切片

分片提取相应部分数据

s[start:end:step]    从start开始到end -1结束,步长为step;

          -如果start省略,则从头开始切片;

          -如果end省略,一直切片到字符串最后

  1. s[  ]               获取字符串从开始到结尾的所有元素      
  2. s[ : :-1]        对于字符串进行反转
  3. s[ : ]             对于字符串拷贝

3.成员操作符

成员运算符:

①  in              在该有序数组内

② not     in   不在该有序数组内

返回结果:布尔值

例:

>>>s = "villa"
>>>"o" in s
False
>>>"v" in s
True
>>>"va" in s
False
>>>"vi" in s
True
>>>"la" not in s
False

4.字符串连接

1、str1 + str2

>>>print("villa" + "fcb")
villafcb

2、str1 str2

>>>print("villa" "fcb")
villafcb

3、str1,str2

>>>print("villa","fcb")
villa fcb

4、字符串列表连接  str.join(list)

函数join接受一个列表,燃用用字符串连接列表中的每一个元素;

>>>player = ["mesii","villa","perdo"]
>>>team = 'fcb'
>>>print(team.join(player))
mesiifcbvillafcbperdo

5、字符串乘法

>>>"mesii"*3
'mesiimesiimesii'

6、%连接字符串  

print("%s%s" %(a,b))
villafcb

5.字符串常用方法

判断:

'isalnum'(判断是否为数字和字母)、'isalpha'(判断是否为字母)、'isdigit(判断是否为数字)'、'islower(判断是否为小写字母)'、'isspace'(判断是否为空格)、'istitle'(判断是否为标题)、'isupper'(判断是否为大写字母)
 

转换:

lower(转换为小写字母), upper(转换为大写字母), title(转换为标题),swapcase(大小写字母相互转换)

>>> "Hello".istitle()
True
>>> "hello".istitle()
False
>>> "HelloWorld".istitle()
False
>>> help("HelloWorld".istitle)

>>> "hello".upper()
'HELLO'
>>> "heLlo".lower()
'hello'
>>> "heLlo".title()
'Hello'
>>> "heLlo".swapcase()
'HElLO'

6.字符串的搜索和替换

find:检查字符串中是否包含字符串
replace:用新字符new替换字符串中的字符old。如果指定第三个参数max,则替换不超过 max 次。
count:统计字符串中某字符出现的次数

>>> s = "hello python , learn python"
>>> s.find('python')
6
>>> s.rfind('python')
21
>>> s.replace('python', 'linux')
'hello linux , learn linux'
>>> s
'hello python , learn python'
>>> s1 = s.replace('python', 'linux')
>>> s1
'hello linux , learn linux'
>>> s
'hello python , learn python'

>>> s.count("python")
2
>>> s.count("p")
2
>>> s.count("i")
0

7.字符串中的分离和拼接

split:通过制定分隔符对字符串进行分割,如果,参数num有指定值,仅分割Num 个字符串
join:将序列中的元素与指定的字符串连接成一个新的字符串

>>> ip = "172.25.254.19"
>>> ip1 = "1172.25.254.19"
>>> help(ip1.split)

>>> ip1.split('.')
['1172', '25', '254', '19']
>>> date = "2018-2-30"
>>> date.split("-")
['2018', '2', '30']
>>> date.replace('-', '/')
'2018/2/30'
>>> ip = ['1172', '25', '254', '19']
>>> "".join(ip)
'11722525419'
>>> ":".join(ip)
'1172:25:254:19'
>>> "*".join(ip)
'1172*25*254*19'

8.开头和结尾匹配

endswith                         结尾匹配
startswith
                        开头匹配

filename = input("请输入文件名:")
if filename.endswith(".log"):
	print(filename)
else:
	print("error file")

 

9.去掉两边空格

strip               去掉两边空格
lstrip              去掉左边空格
rstrip
              去掉右边空格

注意: 去除左右两边的空格, 空格为广义的空格, 包括: \n, \t, \r

例:

>>>s = "\nvilla\n"
>>>s
'\nvilla\n'
>>>print(s)

villa

>>>s = s.strip()
>>>print(s)
villa
>>>s = "\nvilla\n"
>>>s = s.lstrip()
>>>print(s)
villa

>>>s = "\nvilla\n"
>>>s = s.rstrip()
>>>print(s)

villa

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值