python学习之数据类型—字符串string

#!/usr/bin/python

#-*-  encoding:UTF-8 -*-

#date:20180512

Python数据类型

字符串:string

       1、字符串一旦创建就不允许修改,所谓的for循环拿到的是创建了一个新的字符串

learn_str = "   mycounTry
m{}is{}abYeytuff中国   	"
learn_str.capitalize() #字符串首字母大写,其它字母都变成小写
learn_str.center(29,"*")#******mycoutryisabetuff******指定总长度居中显示
learn_str.count("y",5,20)#2 ‘y’在指定范围内出现的次数
learn_str.encode('gbk')#b'mycoutryisabyetuffxd6xd0xb9xfa' 编码为gbk
learn_str.endswith("")#True 以什么结尾,返回True 或 False
learn_str.startswith("x")#False  以什么开头 ,返回值为True或者False,无需比较
learn_str.find("sa")#9   查询目标字符的位置,没找到返回-1,如果出现相同字符,后面的索引会显示前面的索引
learn_str.index("")#22 指定字符的索引位置,没找到报错,如果出现相同字符,后面的索引会显示前面的索引
learn_str.format(111,2222)#mycoutry111is2222abyetuff 中国格式化字符串
learn_str.join("dd")#dmycoutry{}is{}abyetuff中国d join括号里必须是可迭代的对象如列表或字符串,字符串拼接
learn_str.upper()#将小写改为大写
learn_str.lower()
learn_str.replace("my","MP")#MPcouTrym{}is{}abYeytuff中国 将字符串中指定字符改为目标字符
learn_str.strip()#去掉字符串左右的换行,空格,制表符等
learn_str.lstrip()#去掉字符串左的换行,空格,制表符等
learn_str.rstrip()#去掉字符串右的换行,空格,制表符等
learn_str.split("T")#['   mycou', 'rym{}is{}abYeytuff中国   	']指定已什么进行分割,返回一个列表
learn_str.splitlines(True)#['   mycouTry
', 'm{}is{}abYeytuff中国   	']以换行符分割,是否保留字符串中的换行符如
,默认False不保留,可括号中指定True保留
learn_str.isalnum()# 判断字符串存在且全为字母或数字
learn_str.isalpha()# 判断字符串存在且全为字母
learn_str.isdigit()#False 判断字符串全为数字
max(learn_str)#判断字符串中最大的字母
min(learn_str)#判断字符串中最小的字母
learn_str.swapcase()#大小写互换
learn_str.title()#以非字母分割的如特殊字符或数字转换成首字母大写其它都变成小写#Mycoutry M{}Is{}Abyeytuff中国

#字符串一般通过索引来找字符str[index],str是iterable,故可遍历

#字符串可以通过split()和列表中extend()方法 转化成列表

#重复打印字符串 str * int = strstr……
字符串常用方法

 如果想得到字符串中相同元素出现的索引位置,可通过for循环拿到:

  index_n = 0

  for  i  in str:

    if  i  =="目标元素":

         print(index_n)

    index_n  +=1

注:for循环列表,元组,字符串,字典时,内部其实都是 通过指针即索引来以0开始从左至右来循环遍历相应元素进行指向的。

  创建    

str_01 = 'Hello world'

  删除    

del str_01,str_02

   拼接  

#1、通过“+” 来将两个字符串进行拼接
str_01 = 'hello'
str_02 = 'world'
new_str = str_01 + str_02
print(new_str)
>>>helloworld
#2、通过join.()方法(括号中只能是一个序列)
str_01 = 'hello'
str_02 = 'world'
list_str = [str_01,str_02]
new_str = '****'.join(list_str)
print(new_str)
>>>hello****world
'''注:通过“+”进行拼接,缺点是浪费内存,不建议使用,python中的字符串在C语言中体现为是一个字符数组,
每次创建字符串时候需要在内存中开辟一块连续的空间,并且一旦需要修改字符串的话,就需要再次开辟空间,
万恶的 + 号每出现一次就会在内从中重新开辟一块空间。
'''

   切片

str_01 = 'hello world'
print(str_01[0:])#获取从第一个到最后的字符串,第一个字符从零开始计算
print(str_01[:])#获取整个字符串
print(str_01[-3:])#从倒数第三个字符开始到最后的字符即rld
print(str_01[3:7])#获取第四个字符开始到第六个字符即lo w

   分割 

#简单的分割用方法split,不能做多个条件的分割,指定特点的分割符对字符串进行切片分割为一个列表
Phone_Number = '400-300-200-1234'
print(Phone_Number.split('-'))
>>>['400', '300', '200', '1234']
print(Phone_Number.split('-',2))
>>>['400', '300', '200-1234']
'''
注:split是从左向右,以分割符,切片
        rsplit是从右向左,以分隔符,切片
        splitlines 是按照行('
', '
', 
')分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不包含换行符,如果为 True,则保留换行符。
'''
str1 = 'ab c

de fg
kl
'
print (str1.splitlines())
>>>['ab c', '', 'de fg', 'kl']
str2 = 'ab c

de fg
kl
'
print (str2.splitlines(True))
>>>['ab c
', '
', 'de fg
', 'kl
']
#复杂的分割
#r表示不转义,分隔符可以是;或者,或者空格后面跟0个多个额外的空格,然后按照这个模式去分割
#  转义符
#
  换行
#v
#	  tab制表符
#
  回车
#s 匹配任意空白字符
#r或R 按字符串本来的意思输出 即  r'
' -->

import re
line = 'hello world;     python,  I  ,like,       it'
print(re.split(r'[;,s]s*',line))
>>>['hello world', 'python', 'I  ', 'like', 'it']
#正则表达式中*表示匹配前面字符0次或多次

   格式化

print("%s python is %s ok!"%("my","me"))
#>>>my python is me ok!
#另一种格式化表达方式,通过{}和: 来代替%
#通过方法str.formart(),支持位置不按顺序顺序
print("{}{}".format("hello	","china"))
#>>>hello    china
print("{1} {0} {1}".format("hello","china"))
#>>>china hello china
#可配置参数
print("网站名:{name} ,地址:{url}".format(name="学习Python" ,url="www.baidu.com"))
#>>>网站名:学习Python ,地址: www.baidu.com
注:%s 表示字符串
%d 表示数字
  %f 表示浮点型

   字符串的开头和结尾的处理 

字符串的开头和结尾的处理
'''
比方我们要查一个文件的名字是以什么开头或者什么结尾
方法为:
str.startswith()
str.endswith()
'''
file_name = 'hello world2018.txt'
print(file_name.startswith('H'))
#>>>False
print(file_name.endswith('txt'))
#>>>True

   字符串的查找和匹配 

''
一般查找
我们可以很方便的在长的字符串里面查找子字符串,
会返回子字符串所在位置的索引, 若找不到返回-1
'''
file_name = 'hello world2018.txt' print(file_name.find('ll')) >>>2 print(file_name.find('ld')) >>>9 ''' 复杂查找 ''' t_date = '2018/05/12' import re if re.match(r'd+/d+/d+',t_date): print('ok,match') else: print('no march') >>>ok,match
注:+ 正则表达式中表示匹配前面字符一次或多次

  字符串的替换

"""普通替换的方法:str.replace()"""
str_04 = 'python is a easy language,but if you want to learn it ,you should keep up write code everyday!'
str_new = str_04.replace('easy','difficult')
print(str_new,'
',str_04)
#>>>python is a difficult language,but if you want to learn it ,you should keep up write code everyday!
#         python is a easy language,but if you want to learn it ,you should keep up write code everyday!
"""复杂的需要处理多个替换方法:re.sub()"""
my_home = 'man 75 , girl 60'
print(re.sub(r'd+','70',my_home))
#>>>man 70 , girl 70

  去掉字符串中的一些字符

'''
简单去掉文本行中的空格或制表符或换行符
'''
line = '  hello world  2018@python.  '
print(line.strip())#去除字符串左右的空格等符,内部的空格无法去掉,需要用re模块
'''
复杂文本清理str.translate
先构建一个转换表,table是一个翻译表,表示将小写't','o'改为大写'T','O'
然后在old_str里面去掉'eas',然后剩下的字符串再通过table翻译
'''
old_str = 'welcom to our world@2018,is a easy world!'
in_str = 'to'#字符串中要替代的字符组成的字符串,只要是小写‘t’和‘o’都会改变成大写
out_str = 'TO'#相应的映射字符的字符串
table = str.maketrans(in_str,out_str,'eas')
new_str = old_str.translate(table)
print(new_str)
>>>wlcOm TO Our wOrld@2018,i  y wOrld!

注:py2 与 py3  maketrans和translate有区别,详见http://www.runoob.com/python3/python3-string-maketrans.html
原文地址:https://www.cnblogs.com/sunxiuwen/p/8999550.html