字符串

字符串是由字符所组成的一种序列。创建字符串可用""" """、" "和' '

python中字符串是不可变对象,所以所有修改和生成字符串的操作的实现方法都是另一个内存片段中新生成一个字符串对象。

字符串方法:

查看字符串方法

In [2]: print(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']

常用字符串方法介绍

可以参看骏马金龙整理的 https://www.cnblogs.com/f-ck-need-u/archive/2018/06/03/9127699.html

字符串拼接 

加号+拼接

  "abc"+"123" 得 "abc123"

%s拼接

  "I'm a %s,are you %s ?" % ("teacher","OK") 得"I'm a teacher,are you OK ?" ,%s可指代任何对象

  类似的还有%d指代数字,%.nf指代浮点数,n代表精确到小数点后第n位

  还可以用键值对指代 "I'm a %(s)s,are you %(t)s ?" % {'s':'teacher'},'t':'OK'}

format拼接

  "I am {},age {}".format('Roy',10000),{}会被填充得'I am Roy,age 10000'

posted @ 2018-09-25 09:39  Roygood  阅读(163)  评论(0编辑  收藏  举报