python字符串处理

Posted

tags:

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

字符串处理绝对是任何一门语言的重点。

str.partition(sep)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

mystr = hello,!!!world
print(mystr.partition(,))
# output
(hello, ,, !!!world)

str.split(sep=Nonemaxsplit=-1)

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

技术分享

str.join(iterable)

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

mylist = [first, second, third]
mystr = #.join(mylist)
print(mystr)
# output: first#second#third

str.startswith(prefix, start, end)

Return True if string starts with the prefix, otherwise return Falseprefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

mystr = "this is string example....wow!!!"
print(mystr.startswith(this))
print(mystr.startswith(is, 2, 4))
print(mystr.startswith(this, 2, 4))

输出如下:

True
True
False

 



以上是关于python字符串处理的主要内容,如果未能解决你的问题,请参考以下文章

python常用代码片段总结

你如何在 python 中处理 graphql 查询和片段?

常用python日期日志获取内容循环的代码片段

CSP核心代码片段记录

片段(Java) | 机试题+算法思路+考点+代码解析 2023

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