python基础之字符串死磕

先来看看什么是字符串:
大多数程序都定义并收集某种数据,然后使用它们来做些有意义的事情。鉴于此,对数据进行分类大有裨益。我们将介绍的第一种数据类型是字符串。字符串虽然看似简单,但能够以很多不同的方式使用它们。字符串就是一系列字符。在Python中,用引号括起的都是字符串,其中的引号可以是单引号,也可以是双引号
————转自《python编程从入门到实践》
以上解释在我看来是比较易懂的了,如果想要深入理解字符串大家就看看各个编码标准吧,比如’utf-8’,‘ANSI’,‘ASCII’,反正我看了是头大,想自虐的就去看看吧。我是头大。

str1='abdccds'这是字符串
str2="abcdssja"这也是字符串
str3='abc 234 FFFF@@'这也是字符串
字符串都有哪些方法呢:
一条命令搞定
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', 'isascii', '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']

好开心,字符串居然有这么多方法,
**那什么是方法呢,方法就是他能做点什么,函数呢,函数就是我能对他做点什么。**终于说出一句像点样的学习成果了开心啊!!!
来我们来一起按个把玩一下!!!

首先前面__和后面有__的方法我们不要去纠结他,
现在我们层次还很low,还不适合去追求他们。
我们要把注意力放在下面这些方法上。
'capitalize','casefold','center','count','encode',
'endswith', 'expandtabs', 'find','format', 
'format_map', 'index', 'isalnum','isalpha', 
'isascii', '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'

我们怎么使用字符串方法呢?
“字符串”.方法名(参数)==》》》‘hahah’.upper()就是这样。
这写字符串方法都有什么用呢?

很简单一个函数搞定
help(str.upper)
输出结果:
---------------------------------------------------
Help on method_descriptor:
upper(self, /)
    Return a copy of the string converted to uppercase.
--------------------------------------------------------
    **返回转换为大写的字符串的副本。(转自百度翻译)**
    
    我们来试一试这个方法:
    'abddddAAAA123'.upper()
    返回的结果:'ABDDDDAAAA123'
    字符串完全变成了大写,
    这就是这个方法做的,不需要任何参数。
    自学一定要多看文档,顺便学下英文。

大家可以在控制台,使用help函数再看一看其他方法的用法和作用,比如title(),比如capitalize(),还有casefold()。
今天我们先到这里,还是要多动手,勤动脑,还要多洗手,勤通风。

发布了23 篇原创文章 · 获赞 5 · 访问量 382

猜你喜欢

转载自blog.csdn.net/weixin_43287121/article/details/104505297