Python入门教程2. 字符串基本操作【运算、格式化输出、常用函数】 原创
前面简单介绍了Python基本运算,这里再来简单讲述一下Python字符串相关操作
1.字符串表示方法
>>>"www.nhooo.com"#字符串使用单引号(')或双引号(")表示 'www.nhooo.com' >>>'www.nhooo.com' 'www.nhooo.com' >>>"www."+"jb51"+".net"#字符串可以用“+”号连接 'www.nhooo.com' >>>"#"*10#字符串可以使用“*”来代表重复次数 '##########' >>>"What'syourname?"#单引号中可以直接使用双引号,同理双引号中也可以直接使用单引号 "What'syourname?" >>>path=r"C:\newfile"#此处r开头表示原始字符串,里面放置的内容都是原样输出 >>>print(path) C:\newfile
2.字符串运算
>>>str1="pythontest" >>>"test"instr1#这里in用来判断元素是否在序列中 True >>>len(str1)#这里len()函数求字符串长度 11 >>>max(str1) 'y' >>>min(str1) ''
3.字符串格式化输出(这里重点讲format函数)
>>>"Ilike%s"%"python"#使用%进行格式化输出的经典表示方式 'Ilikepython' >>>dir(str)#列出字符串所有属性与方法 ['__add__','__class__','__contains__','__delattr__','__dir__','__doc__','__eq__','__format__','__ge__','__getattribute__','__getitem__','__getnewargs__','__gt__','__hash__','__init__','__init_subclass__','__iter__','__le__','__len__','__lt__','__mod__','__mul__','__ne__','__new__','__reduce__','__reduce_ex__','__repr__','__rmod__','__rmul__','__setattr__','__sizeof__','__str__','__subclasshook__','capitalize','casefold','center','count','encode','endswith','expandtabs','find','format','format_map','index','isalnum','isalpha','isdecimal','isdigit','isidentifier','islower','isnumeric','isprintable','isspace','istitle','isupper','join','ljust','lower','lstrip','maketrans','partition','replace','rfind','rindex','rjust','rpartition','rsplit','rstrip','split','splitlines','startswith','strip','swapcase','title','translate','upper','zfill']
①format(*args,**kwargs)采用*args赋值
>>>str="Ilike{1}and{2}"#这里{1}表示占位符(注意:这里得从{0}开始)
>>>str.format("python","PHP")
Traceback(mostrecentcalllast):
File"",line1,in
str.format("python","PHP")
IndexError:tupleindexoutofrange
>>>str="Ilike{0}and{1}"
>>>str.format("python","PHP")
'IlikepythonandPHP'
>>>"Ilike{1}and{0}".format("python","PHP")
'IlikePHPandpython'
>>>"Ilike{0:20}and{1:>20}".format("python","PHP")#{0:20}表示第一个位置占据20个字符,并且左对齐。{1:>20}表示第二个位置占据20个字符,且右对齐
'IlikepythonandPHP'
>>>"Ilike{0:.2}and{1:^10.2}".format("python","PHP")#{0:.2}表示第一个位置截取2个字符,左对齐。{1:^10.2}表示第二个位置占据10个字符,且截取2个字符,^表示居中
'IlikepyandPH'
>>>"age:{0:4d}height:{1:6.2f}".format("32","178.55")#这里应该是数字,不能用引号,否则会被当作字符串而报错!
Traceback(mostrecentcalllast):
File"",line1,in
"age:{0:4d}height:{1:6.2f}".format("32","178.55")
ValueError:Unknownformatcode'd'forobjectoftype'str'
>>>"age:{0:4d}height:{1:8.2f}".format(32,178.5523154)#这里4d表示长度为4个字符的整数,右对齐。8.2f表示长度为8,保留2位小数的浮点数,右对齐。
'age:32height:178.55'
②format(*args,**kwargs)采用**kwargs赋值
>>>"Ilike{str1}and{str2}".format(str1="python",str2="PHP")
'IlikepythonandPHP'
>>>data={"str1":"PHP","str2":"Python"}
>>>"Ilike{str1}and{str2}".format(**data)
'IlikePHPandPython'
小结:对齐方式为:
4.字符串函数
>>>#isalpha()判断字符串是否全部为字母
>>>str1="Ilikepython"#这里str1里面有空格
>>>str1.isalpha()
False
>>>str2="pythonDemo"#这里为全部是字母
>>>str2.isalpha()
True
>>>#split()分割字符串
>>>smp="IlikePython"
>>>smp.split("")
['I','like','Python']
>>>#strip()去除字符串两端空格,类似的,lstrip去除左侧空格,rstrip去除右侧空格
>>>strDemo="pythondemo"
>>>strDemo.strip()#类似于php中的trim()函数
'pythondemo'
>>>"****python**".strip("*")#strip()函数还可删除指定字符
'python'
字符串常用函数【转换、判断】
>>>#字符串拼接(对于+不适用的情况下可以使用)
>>>smp="IlikePython"
>>>c=smp.split("")
>>>c="Ilikepython".split()
>>>type(c)#这里检测类型,可以看到c为列表
>>>"*".join(c)
'I*like*Python'
>>>"".join(c)
'IlikePython'
>>>"".join(["I","Like","python"])#这里可以直接使用列表作为join函数的参数
'ILikepython'
>>>"".join("abcd")#也可直接使用字符串作为join函数的参数
'abcd'
>>>#count()函数统计指定字符串出现次数
>>>"likepython,learnpython".count("python")
2
>>>#find()函数查找指定字符串出现位置
>>>"pythonDemo".find("python")
0
>>>"pythonDemo".find("Demo")
7
>>>#replace(old,new)函数替换指定字符串(old)为新字符串(new)
>>>"Ilikephp".replace("php","python")
'Ilikepython'
简单入门教程~
基本一看就懂~O(∩_∩)O~
未完待续~~欢迎讨论!!