Python3字符串魔法(函数)

目录

文章目录

2. capitalize(self)方法

说明:将字符串首字母变大写,其余字母全部变小写
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="sNow"
a=test.capitalize()
print(a)

运行结果如下:

Snow

3. lower(self)方法

说明:将字符串所有字母全部变小写
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="sNow"
a=test.lower()
print(a)

运行结果如下:

snow

4. casefold(self)方法

说明:将字符串所有字母以及其他我们不知道的特殊字符全部小写(功能更强大)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="sNow"
a=test.casefold()
print(a)

运行结果如下:

snow

5. center(self, __width, __fillchar) 方法

说明:将字符串总宽度设置为20,并将字符串居中,两边默认用空白填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
# _fillchar 填充字符(可以是数字、字母、中文、特殊符号、但只能是一个)
test="sNow"
a=test.center(20)
print(a)

运行结果如下:

        sNow        
说明:将字符串总宽度设置为20,并将字符串居中,两边用中文字“中”进行填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
# _fillchar 填充字符(可以是数字、字母、中文、特殊符号、但只能是一个)
test="sNow"
a=test.center(20,"中")
print(a)

运行结果如下:

中中中中中中中中sNow中中中中中中中中

6. ljust(self, __width, __fillchar) 方法

说明:将字符串总宽度设置为20,并将字符串居左,右边不够剩下的长度默认用空白填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
# _fillchar 填充字符(可以是数字、字母、中文、特殊符号、但只能是一个)
test="sNow"
a=test.ljust(20)
print(a)

运行结果如下:

sNow                
说明:将字符串总宽度设置为20,并将字符串居左,右边不够剩下的长度用中文字“中”进行填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
# _fillchar 填充字符(可以是数字、字母、中文、特殊符号、但只能是一个)
test="sNow"
a=test.ljust(20,"中")
print(a)

运行结果如下:

sNow中中中中中中中中中中中中中中中中

7. rjust(self, __width, __fillchar) 方法

说明:将字符串总宽度设置为20,并将字符串居居右,左边剩下的长度默认用空白填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
# _fillchar 填充字符(可以是数字、字母、中文、特殊符号、但只能是一个)
test="sNow"
a=test.rjust(20)
print(a)

运行结果如下:

                sNow             
说明:将字符串总宽度设置为20,并将字符串居右,左边剩下的长度用中文字“中”进行填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
# _fillchar 填充字符(可以是数字、字母、中文、特殊符号、但只能是一个)
test="sNow"
a=test.rjust(20,"中")
print(a)

运行结果如下:

中中中中中中中中中中中中中中中中sNow

8. zfill(self, __width) 方法

说明:将字符串总宽度设置为20,并将字符串居居右,左边剩下的长度默认用0填充
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# _width 设置字符串总宽度
test="sNow"
a=test.zfill(20)
print(a)

运行结果如下:

0000000000000000sNow             

9. count(self, x, __start, __end)方法

说明:在字符串中计算子字符串的个数,默认从字符串最左边一位计算到结束(不包括结束)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="sNownnr"
a=test.count("n")
print(a)

b=test.count("w")
print(b)

运行结果如下:

2
1
说明:在字符串中计算子字符串的个数,默认在字符串某个范围内计算

注意:字符串下标是从1开始,范围的时候是前闭后开区间

#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="snowsnow" 
a=test.count("no",5) #指定位置到结束(不包括结束)
print(a)

b=test.count("no",5,6)
print(b)

c=test.count("no",5,7)
print(c)
运行结果如下:
```python
1
0
1

10. encode(self,encoding,errors)方法

说明:以指定的编码格式编码当前输入的内容。errors参数可以指定不同的错误处理方案。
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="我是yuki$"
result=test.encode("UTF-8")
print(result)

result=test.encode("GBK")
print(result)

运行结果如下:

b'\xe6\x88\x91\xe6\x98\xafyuki$'
b'\xce\xd2\xca\xc7yuki$'

11. decode(self)方法

说明:

12. startswith(self,suffix,start,end)方法

说明:判断是否以子字符串开始(默认从最左边一位到结束,也可以自定义从哪个位置开始进行判断)

注意:字符串下标是从1开始,范围的时候是前闭后开区间

#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="yukiyuki"
flag=test.startswith("F")
print(flag)

flag=test.startswith("y")
print(flag)

flag=test.startswith("i",3)
print(flag)

flag=test.startswith("iy",3,4)
print(flag)

运行结果如下:

False
True
True
False

13. endswith(self,suffix,start,end)方法

说明:判断是否以子字符串结尾默认从最左边一位到结束(也可以自定义从哪个位置开始进行判断)

注意:字符串下标是从1开始,范围的时候是前闭后开区间

#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="yukiyuki"
flag=test.endswith("F")
print(flag)

flag=test.endswith("i")
print(flag)

flag=test.endswith("i",3)
print(flag)

flag=test.endswith("iy",3,4)
print(flag)

flag=test.endswith("iy",3,5)
print(flag)

运行结果如下:

False
True
True
False
True

14. expandtabs(self,tabsize)方法

说明:将当前输入的表格化,每个单元格长度为20
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

# tabsize 设置表格单元格长度
# tabsize 数字比里面内容长度大
test="username\temail\tpassword\nyuki\t123456@qq.com\tyuki123456\nblackcat\t654321@qq.com\tblackcat123456\n"
a=test.expandtabs(20)
print(a)

运行结果如下:

username            email               password
yuki                123456@qq.com       yuki123456
blackcat            654321@qq.com       blackcat123456

15. find(self, sub, __start, __end)方法

说明:从字符串左边第一位开始往后查找指定子字符串,找到第一个之后,获取其位置(也可以自定义从哪个位置开始进行查找)

注意:字符串下标是从1开始,范围的时候是前闭后开区间
注意:如果找不到子字符串,结果返回-1

#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="yukiyuki"
index=test.find("k")
print(index)

index=test.find("ki",6)
print(index)

index=test.find("ki",6,7)
print(index)

index=test.find("ki",6,8)
print(index)

index=test.find("ki",6,9)
print(index)

运行结果如下:

2
6
-1
6
6

16. index(self, sub, __start, __end)方法

说明:从字符串左边第一位开始往后查找指定子字符串,找到第一个之后,获取其位置(也可以自定义从哪个位置开始进行查找)

注意:字符串下标是从1开始,范围的时候是前闭后开区间

#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="yukiyuki"
index=test.index("k")
print(index)

index=test.index("ki",6)
print(index)

index=test.index("ki",6,8)
print(index)

index=test.index("ki",6,9)
print(index)

运行结果如下:

2
6
6
6
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="yukiyuki"
index=test.index("ki",6,7)
print(index)

注意:如果找不到子字符串,会报错,从报错的地方开始后面的代码都不会只执行,所以我们一般都不使用这个方法,使用find(self, sub, _start, _end)方法会更好

运行结果如下:

Traceback (most recent call last):
  File "E:/softwares/python/pythonProject/day20200802/helloWorld.py", line 10, in <module>
    index=test.index("ki",6,7)
ValueError: substring not found

17. format(self, args, kwargs)方法

说明:格式化,将一个字符串中的占位符替换为指定的值
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="i am {name},i am {age} years old"
print(test)
result1=test.format(name="yuki",age=18)
print(result1)

a="i am {0},i love {1}"
result2=a.format("blackcat","one piece")
print(result2)

运行结果如下:

i am {name},i am {age} years old
i am yuki,i am 18 years old
i am blackcat,i love one piece

18. format_map(self, args, kwargs)方法

说明:格式化,将一个字符串中的占位符替换为指定的值
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


# 格式化,传入的值 {"name": 'alex', "a": 19}
test="i am {name},i am {age} years old"
result1 = test.format(name='yuki',age=10)
result2 = test.format_map({"name": 'blackcat', "age": 19})
print(result1)
print(result2)

运行结果如下:

i am yuki,i am 10 years old
i am blackcat,i am 19 years old

19. isalpha(self)方法

说明:判断当前输入是否是字母、中文、以及字母+中文的形式
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#



test="adrf12d_$"
result = test.isalpha()
print(result)

test="adrf12d"
result = test.isalpha()
print(result)


test="sdsR"
result = test.isalpha()
print(result)

test="中"
result = test.isalpha()
print(result)


test="中af"
result = test.isalpha()
print(result)

test="中af12"
result = test.isalpha()
print(result)

运行结果如下:

False
False
True
True
True
False

20. isalnum(self)方法

说明:判断当前输入是否是字母、数字、中文、以及他们相互组合的形式
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#



test="中af12"
result = test.isalnum()
print(result)

test="a"
result = test.isalnum()
print(result)

test="12"
result = test.isalnum()
print(result)

test="二"
result = test.isalnum()
print(result)

test="②"
result = test.isalnum()
print(result)

运行结果如下:

True
True
True
True
True
True

21. isdecimal(self)方法

说明:判断当前输入是否是数字(十进制数字)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#



test="中af12"
result = test.isdecimal()
print(result)

test="a"
result = test.isdecimal()
print(result)

test="12"
result = test.isdecimal()
print(result)

test="二"
result = test.isdecimal()
print(result)

test="②"
result = test.isdecimal()
print(result)

运行结果如下:

False
False
True
False
False

22. isdigit(self)方法

说明:判断当前输入是否是数字(十进制数字、特殊表达方式的数字)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#



test="中af12"
result = test.isdigit()
print(result)

test="a"
result = test.isdigit()
print(result)

test="12"
result = test.isdigit()
print(result)

test="二"
result = test.isdigit()
print(result)

test="②"
result = test.isdigit()
print(result)

运行结果如下:

False
False
True
False
True

23. isnumeric(self)方法

说明:判断当前输入是否是数字(十进制数字、特殊表达方式的数字、汉字数字)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#



test="中af12"
result = test.isnumeric()
print(result)

test="a"
result = test.isnumeric()
print(result)

test="12"
result = test.isnumeric()
print(result)

test="二"
result = test.isnumeric()
print(result)

test="②"
result = test.isnumeric()
print(result)

运行结果如下:

False
False
True
True
True

24. isprintable(self)方法

说明:判断当前输入是否存在不可显示的字符
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="oiuas\tdfkj\nle23"
# \t   制表符,当作可显示的字符
# \n   换行符,当作可显示的字符
result=test.isprintable()
print(result)

运行结果如下:

False

25. isspace(self)方法

说明:判断当前输入是否全部是空格
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="oiuas\tdfkj\nle23"
# \t   制表符,当作可显示的字符
# \n   换行符,当作可显示的字符
result=test.isspace()
print(result)

test="  "  #两个空格
result=test.isspace()
print(result)

test="		" #两个tab键
result=test.isspace()
print(result)

运行结果如下:

False
True
True

26. istitle(self)方法

说明:判断当前输入是否是标题并进行标题转换
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="oiuas\tdfkj\nle23"
# \t   制表符,当作可显示的字符
# \n   换行符,当作可显示的字符
result=test.istitle()
print(result)
test=test.title()  #转换当前输入为标题格式
print(test)


test = "Return True if all cased characters in S are uppercase and there is"
result=test.istitle()
print(result)
test=test.title()  #转换当前输入为标题格式
print(test)

运行结果如下:

False
Oiuas	Dfkj
Le23
False
Return True If All Cased Characters In S Are Uppercase And There Is

27. islower(self)方法

说明:判断当前输入是否全部是小写并进行全部小写转换
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="adeF  D"
print(test)
flag=test.islower()
result=test.lower()
print(flag,result)

运行结果如下:

adeF  D
False adef  d

28. isupper(self)方法

说明:判断当前输入是否全部是大写并进行全部大写转换
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="adeF  D"
print(test)
flag=test.isupper()
result=test.upper()
print(flag,result)

运行结果如下:

adeF  D
False ADEF  D

29. isupper(self)方法

说明:将当前输入大写字母转换成小写,小写字母转换成大写
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="adeF 中 D"
print(test)
result=test.swapcase()
print(result)

运行结果如下:

adeF 中 D
ADEf 中 d

30. isidentifier(self)方法

说明:判断当前输入是否是标识符
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="def"
result=test.isidentifier()
# 什麽是标识符:  def  class,以下划线开头的......
# 凡是不能当作变量名的都可以算为标识符
print(result)

test="class"
result=test.isidentifier()
print(result)

test="def"
result=test.isidentifier()
print(result)

test="_x123"
result=test.isidentifier()
print(result)

test="1_x123"
result=test.isidentifier()
print(result)

test="*_x123"
result=test.isidentifier()
print(result)

运行结果如下:

True
True
True
True
False
False

32. strip(self,__chars)方法

说明:删除字符串中指定的内容,只删除头和尾匹配上的,中间的不会删除
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="snowsnowex"
a=test.strip("sn")
print(a)

a=test.strip("ex")
print(a)

a=test.strip("no")
print(a)

运行结果如下:

owsnowex
snowsnow
snowsnowex

33. lstrip(self,__chars)方法

说明:删除字符串中指定的内容,只最左边匹配上的,其他的不会删除
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="snowsnowex"
a=test.lstrip("sn")
print(a)

a=test.lstrip("ex")
print(a)

a=test.lstrip("no")
print(a)

运行结果如下:

owsnowex
snowsnowex
snowsnowex

34. rstrip(self,__chars)方法

说明:删除字符串中指定的内容,只最右边匹配上的,其他的不会删除
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="snowsnowex"
a=test.rstrip("sn")
print(a)

a=test.rstrip("ex")
print(a)

a=test.rstrip("no")
print(a)

运行结果如下:

snowsnowex
snowsnow
snowsnowex

35. maketrans(intab, outtab)方法

说明:创建字符映射的转换表

36. partition(self, __sep)方法

说明:将当前输入以指定的内容分割为3部分(从左往右匹配第一个)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="yukaisyuki"
result=test.partition("i")
print(result)
result=test.partition("is")
print(result)

运行结果如下:

('yuka', 'i', 'syuki')
('yuka', 'is', 'yuki')

37. rpartition(self, __sep)方法

说明:将当前输入以指定的内容分割为3部分(从右往左匹配第一个)
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="yukaisyuki"
result=test.rpartition("i")
print(result)
result=test.rpartition("is")
print(result)

运行结果如下:

('yukaisyuk', 'i', '')
('yuka', 'is', 'yuki')

38. split(self, sep, maxsplit)方法

说明:通过指定分隔符对字符串进行切片,如果参数 maxsplit有指定值,则分隔 maxsplit+1 个子字符串
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="yukai"
result=test.split("i",2)
print(result)

test="yukaisyuki"
result=test.split("i",2)
print(result)

test="yukaisyukia123ede"
result=test.split("i",2)
print(result)

运行结果如下:

['yuka', '']
['yuka', 'syuk', '']
['yuka', 'syuk', 'a123ede']

39. splitlines(self, keepends)方法

说明:按照(’\r’, ‘\r\n’, \n’)分隔,返回一个包含各行作为元素的列表,如果参数 keepends 为 False,不保留分割符,如果为 True,则保留分割符。
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="yukais\ryukia\n123\r\nede"
result=test.splitlines(False)
print(result)

result=test.splitlines(True)
print(result)

运行结果如下:

['yukais', 'yukia', '123', 'ede']
['yukais\r', 'yukia\n', '123\r\n', 'ede']

40. replace(self,__old,__new,__count)方法

说明:把字符串中的 __old(旧字符串) 替换成 __new(新字符串),如果指定第三个参数__count,则替换不超过 __count 次。
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#

test="yukaisyukia1yuki23yukiede"
result=test.replace("uk","$")
print(result)

result=test.replace("uk","$",2)
print(result)

运行结果如下:

y$aisy$ia1y$i23y$iede
y$aisy$ia1yuki23yukiede

41. join(self,__iterable)方法

说明:将当前输入的每一个元素按照指定分隔符进行拼接
#!/usr/bin/python
# -*- coding:utf-8 -*-
# created by yuki
#


test="你是风儿我是沙"
print(test)
result="*".join(test)
print(result)

result="_".join(test)
print(result)

result=" ".join(test)
print(result)

result="\t".join(test)
print(result)

result="\n".join(test)
print(result)

运行结果如下:

你是风儿我是沙
你******沙
你_是_风_儿_我_是_沙
你 是 风 儿 我 是 沙
你	是	风	儿	我	是	沙
你
是
风
儿
我
是
沙
Python中的魔法函数是以双下划线开头和结尾的函数,可以让我们自由地定义自定义类的特性。这些魔法函数在Python中有多种用途,比如实现运算符重载、属性访问控制、对象创建和初始化等。通过定义魔法函数,我们可以为自己的类增加一些特殊的行为和功能。 例如,__new__()方法是一个特殊的魔法函数,在创建新对象时隐式调用。它返回一个新的对象,并在之后由__init__()方法初始化该对象。__init__()方法用于初始化对象的属性和状态。这两个魔法函数通常是在类的定义中同时使用的。 另外,__str__()方法也是一个常用的魔法函数,用于返回对象的字符串表示。通过在类中定义__str__()方法,我们可以自定义对象的字符串表达形式,使其更易于阅读和理解。 总结来说,Python的魔法函数是一种特殊的函数,通过以双下划线开头和结尾的命名规则,可以实现自定义类的特性和行为。这些魔法函数在Python中有广泛的应用,包括运算符重载、属性访问控制、对象创建和初始化等方面。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [17.Python中的魔法函数](https://blog.csdn.net/bai666ai/article/details/123974233)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值