学习笔记(05):600 分钟搞定 Python 入门到实战-字符和字符串-3

立即学习:https://edu.csdn.net/course/play/26676/338776?utm_source=blogtoedu

五、查看字符串的属性及方法
1、dir()内置函数:查看对象属性
>>> dir(str)

>>> s = "python lesson"
>>> dir(s)
2、help()内置函数:查看对象帮助及使用说明,python语言中函数也是对象,万物皆对象。
3、S.index(sub[, start[, end]]) -> int,字符串函数:返回子串sub在主串S中的最小起始位,若S不包含sub,则触发异常。
>>> help(s.index)
Help on built-in function index:

index(...) method of builtins.str instance
    S.index(sub[, start[, end]]) -> int

    Return the lowest index in S where substring sub is found,
    such that sub is contained within S[start:end].  Optional
    arguments start and end are interpreted as in slice notation.

    Raises ValueError when the substring is not found.(找不到返回异常)

>>> s
'python lesson'
>>> s.index('n')
5
>>> s.index('n',6)
12
>>> s.index('on')
4
>>> 
4、S.split(sep=None, maxsplit=-1) -> list of strings:返回字符串S中包含的单词列表
>>> s.split()
['python', 'lesson']
>>> list = s.split()
>>> list = s.split("")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: empty separator
>>> list = s.split(" ")
>>> list
['python', 'lesson']
>>> 
5、S.join(iterable) -> str:将字符串列表中的每个元素用S连接成一个字符串
>>>"_".join(list)
'python_lesson'
>>>
6、S.format(*args, **kwargs) -> str:字符串的格式化输出
6.1、  {0}、 {1}使用format()方法中的参数代替,参数索引从0依次编号
>>>"I like {0} and {1}" format("python","physics")
  File "<stdin>", line 1
    "I like {0} and {1}" format("python","physics")
                              ^
SyntaxError: invalid syntax
>>>"I like {0} and {1}" .format("python","physics")
'I like python and physics'
>>>
6.2、 {0:10}:参数0显示10位定长字符,默认左对齐;{1:>15}:参数1显示5位定长,字符右对齐,右对齐格式'>'书写位置不可随意。
>>>"I like {0:10} and {1:>15}" .format("python","physics")
'I like python     and         physics'
>>> 
6.3、{0:^10} :参数0显示10位定长字符,居中对齐
>>> "I like {0:^10} and {1:>15}" .format("python","physics")
>>>
6.4、{0:4d}:参数0显示4位定长整数,默认右对齐;{1:.1f}:参数0显示四舍五入后精度位1位的浮点数,默认右对齐
>>> "She is {0:4d} years old and {1:.1f} in height".format(28,1.68)
'She is   28 years old and 1.7 in height'
>>>
6.5、
>>> "She is {1:4f} years old and {0:.1f} in height".format(28,1.68)
'She is 1.680000 years old and 28.0 in height'
>>> "She is {1:f} years old and {0:.1f} in height".format(28,1.68)
'She is 1.680000 years old and 28.0 in height'
>>> "She is {1:4d} years old and {0:.1f} in height".format(28,1.68)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: Unknown format code 'd' for object of type 'float'
>>>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值