[Python] 字符串操作

Posted itkeyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Python] 字符串操作相关的知识,希望对你有一定的参考价值。

字符串操作


以下字符串可以  变量.函数()    也可以   "字符串".函数()

 

capitalize()


首字母大写,其余转换为小写

print("test TEST".capitalize())

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
Test test

Process finished with exit code 0

 count()


 count("str"),统计字符串出现的次数,跟列表的用法一样

print("test test".count("t"))

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
4

Process finished with exit code 0

 center()


center(number,"str") 让内容显示在中间,使内容两侧填充字符串,默认是空格

 

print("test".center(50,"-"))

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
-----------------------test-----------------------

Process finished with exit code 0

 

endswith()


 endswith("str"),判断字符串结尾是否包含 “str“,是则True 否则False

print("i am shuaige".endswith("ge"))

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
True

Process finished with exit code 0

 find()


find("str") 查找字符串并返回索引值,如果不存在则返回 -1

print("i am shuaige".find("am"))

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
2

Process finished with exit code 0

 

format_map()


和format用法一样,字符格式化。只是格式不一样

print("my name is {name} i am {age} years old".format_map({"name":"DaHua","age":10}))

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
my name is DaHua i am 10 years old

Process finished with exit code 0

isalnum()


 

str.isalnum()  检查字符串是否仅为字母、数字,或者为字母数字混合,是则返回 True,否则返回 False

print("test123".isalnum())

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
True

Process finished with exit code 0

 

isalpha()


 

str.alpha() 检查字符串是否为字母,是则返回True,否则返回False

print("abc".isalpha())

  输出

C:UsersAdministratorAppDataLocalProgramsPythonPython37python.exe D:/Python/Day02/test.py
True

Process finished with exit code 0

 

isdecimal()


 

str.isdecimal() 检查字符串是否只为十六进制

print("000000".isdecimal())

  输出

 

以上是关于[Python] 字符串操作的主要内容,如果未能解决你的问题,请参考以下文章

学习笔记:python3,代码片段(2017)

Python代码阅读(第25篇):将多行字符串拆分成列表

jQuery的DOM操作

《Python学习之路 -- Python基础之切片》

android小知识点代码片段

[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段