python 字符串函数

Python provides a lot of built-in functions to manipulate strings. Python String is immutable, so all these functions return a new string and the original string remains unchanged.

Python提供了许多内置函数来操纵字符串。 Python字符串是不可变的,因此所有这些函数都返回一个新字符串,并且原始字符串保持不变。

(Python String Functions)

There are many functions to operate on String. However, it’s not feasible to remember all of them. So here I am dividing them into different categories.

有很多函数可对String进行操作。 但是,记住所有这些都是不可行的。 所以在这里我将它们分为不同的类别。

  • Must Know String Functions
  • Good to Know String Functions
  • Miscellaneous String Functions
  • Built-in Functions that work on String
  • Useful String Operations

(Must Know String Functions)

Function

Description

format()

It’s used to create a formatted string from the template string and the supplied values.

split()

Python string split() function is used to split a string into the list of strings based on a delimiter.

join()

This function returns a new string that is the concatenation of the strings in iterable with string object as a delimiter.

strip()

Used to trim whitespaces from the string object.

format_map()

Python string format_map() function returns a formatted version of the string using substitutions from the mapping provided.

upper()

We can convert a string to uppercase in Python using str.upper() function.

lower()

This function creates a new string in lowercase.

replace()

Python string replace() function is used to create a new string by replacing some parts of another string.

find()

Python String find() method is used to find the index of a substring in a string.

translate()

Python String translate() function returns a new string with each character in the string replaced using the given translation table.

功能

描述

格式()

它用于根据模板字符串和提供的值创建格式化的字符串。

分裂()

Python字符串split()函数用于根据定界符将字符串拆分为字符串列表。

加入()

此函数返回一个新字符串,该字符串是使用string对象作为定界符可迭代的字符串的串联。

跳闸()

用于修剪字符串对象中的空格。

format_map()

Python字符串format_map()函数使用提供的映射中的替换返回字符串的格式化版本。

上()

我们可以使用str.upper()函数将字符串转换为大写形式。

降低()

此函数以小写形式创建一个新字符串。

更换()

Python字符串replace()函数用于通过替换另一个字符串的某些部分来创建新字符串。

找()

Python String find()方法用于查找字符串中子字符串的索引。

翻译()

Python字符串translate()函数返回一个新字符串,该字符串中的每个字符都使用给定的转换表替换。

(Good to Know String Functions)

Function

Description

encode()

Python string encode() function is used to encode the string using the provided encoding.

count()

Python String count() function returns the number of occurrences of a substring in the given string.

startswith()

Python string startswith() function returns True if the string starts with the given prefix, otherwise it returns False.

endswith()

Python string endswith() function returns True if the string ends with the given suffix, otherwise it returns False.

capitalize()

Python String capitalize() function returns the capitalized version of the string.

center()

Python string center() function returns a centered string of specified size.

casefold()

Python string casefold() function returns a casefolded copy of the string. This function is used to perform case-insensitive string comparison.

expandtabs()

Python string expandtabs() function returns a new string with tab characters (\t) replaced with one or more whitespaces.

index()

Python String index() function returns the lowest index where the specified substring is found.

__contains__()

Python String class has __contains__() function that we can use to check if it contains another string or not. We can also use “in” operator to perform this check.

功能

描述

编码()

Python字符串encoding()函数用于使用提供的编码对字符串进行编码。

计数()

Python String count()函数返回给定字符串中子字符串出现的次数。

以。。开始()

如果字符串以给定前缀开头,则Python字符串startswith()函数返回True,否则返回False。

以。。结束()

如果字符串以给定的后缀结尾,则Python字符串endswith()函数返回True,否则返回False。

大写()

Python字符串capitalize()函数返回字符串的大写版本。

中央()

Python字符串center()函数返回指定大小的居中字符串。

casefold()

Python字符串casefold()函数返回字符串的casefolded副本。 此函数用于执行不区分大小写的字符串比较。

expandtabs()

Python字符串expandtabs()函数返回一个新的字符串,其中的制表符(\ t)替换为一个或多个空格。

指数()

Python String index()函数返回找到指定子字符串的最低索引。

__包含__()

Python字符串类具有__contains __()函数,我们可以使用该函数检查它是否包含另一个字符串。 我们还可以使用“ in”运算符执行此检查。

(Miscellaneous String Functions)

Function

Description

isalnum()

Python string isalnum() function returns True if it’s made of alphanumeric characters only.

isalpha()

Python String isalpha() function returns True if all the characters in the string are alphabets, otherwise False.

isdecimal()

Python String isdecimal() function returns True if all the characters in the string are decimal characters, otherwise False.

isdigit()

Python String isdigit() function returns True if all the characters in the string are digits, otherwise False.

isidentifier()

Python String isidentifier() function returns True if the string is a valid identifier according to the Python language definition.

islower()

Python String islower() returns True if all cased characters in the string are lowercase and there is at least one cased character, otherwise it returns False.

isnumeric()

Python String isnumeric() function returns True if all the characters in the string are numeric, otherwise False. If the string is empty, then this function returns False.

isprintable()

Python String isprintable() function returns True if all characters in the string are printable or the string is empty, False otherwise.

isspace()

Python String isspace() function returns True if there are only whitespace characters in the string, otherwise it returns False.

istitle()

Python String istitle() returns True if the string is title cased and not empty, otherwise it returns False.

isupper()

Python String isupper() function returns True if all the cased characters are in Uppercase.

rjust(), ljust()

Utility functions to create a new string of specified length from the source string with right and left justification.

swapcase()

Python String swapcase() function returns a new string with uppercase characters converted to lowercase and vice versa.

partition()

Python String partition() function splits a string based on a separator into a tuple with three strings.

splitlines()

Python String splitlines() function returns the list of lines in the string.

title()

Python String title() function returns a title cased version of the string.

zfill()

Python String zfill(width) function returns a new string of specified width. The string is filled with 0 on the left side to create the specified width.

功能

描述

isalnum()

如果Python字符串isalnum()函数仅由字母数字字符组成,则返回True。

isalpha()

如果字符串中的所有字符都是字母,则Python String isalpha()函数将返回True,否则返回False。

isdecimal()

如果字符串中的所有字符均为十进制字符,则Python String isdecimal()函数将返回True,否则返回False。

isdigit()

如果字符串中的所有字符都是数字,则Python String isdigit()函数将返回True,否则返回False。

isidentifier()

如果字符串是根据Python语言定义的有效标识符,则Python String isidentifier()函数返回True。

islower()

如果字符串中所有大小写的字符均为小写且至少有一个大小写的字符,则Python String islower()返回True。否则,返回False。

isnumeric()

如果字符串中的所有字符均为数字,则Python String isnumeric()函数将返回True,否则返回False。 如果字符串为空,则此函数返回False。

isprintable()

如果字符串中的所有字符均可打印或字符串为空,则Python String isprintable()函数将返回True,否则返回False。

isspace()

如果字符串中仅包含空格字符,则Python String isspace()函数将返回True,否则返回False。

istitle()

如果字符串为首字母大写且不为空,则Python String istitle()返回True,否则返回False。

isupper()

如果所有大小写的字符均为大写,则Python String isupper()函数将返回True。

rjust(),ljust()

实用程序功能从源字符串创建带有左右对齐方式的指定长度的新字符串。

swapcase()

Python String swapcase()函数返回一个新字符串,其中大写字符转换为小写,反之亦然。

划分()

Python String partition()函数将基于分隔符的字符串拆分为具有三个字符串的元组。

splitlines()

Python字符串splitlines()函数返回字符串中的行列表。

标题()

Python字符串title()函数返回字符串的标题大小写形式。

zfill()

Python字符串zfill(width)函数返回指定宽度的新字符串。 该字符串在左侧用0填充以创建指定的宽度。

(Built-in Functions that work on String)

Function

Description

len()

Python String length can be determined by using built-in len() function.

ascii()

Python ascii() function returns the string representation of the object. This function internally calls repr() function and before returning the representation string, escapes the non-ASCII characters using \x, \u or \U escapes.

bool()

Python bool() function returns Boolean value for an object. The bool class has only two instances – True and False.

bytearray()

Python bytearray() function returns a bytearray object that contains the array of bytes from the input source.

bytes()

This function returns bytes object that is an immutable sequence of integers in the range 0 <= x < 256.

ord()

Python ord() function takes string argument of a single Unicode character and return its integer Unicode code point value.

enumerate()

Python enumerate function takes a sequence, and then make each element of the sequence into a tuple.

float()

As the name says, python float() function returns a floating point number from the input argument.

hash()

This function returns the hash value of the given object.

id()

Python id() function returns the “identity” of the object. The identity of an object is an integer, which is guaranteed to be unique and constant for this object during its lifetime.

int()

Python int() function returns an integer object from the specified input. The returned int object will always be in base 10.

map()

Python map() function is used to apply a function on all the elements of specified iterable and return map object.

print()

Python print() function is used to print data into console.

slice()

Python slice() function returns a slice object representing the set of indices specified by range(start, stop, step).

type()

This function returns the type of the object.

功能

描述

len()

可以使用内置的len()函数确定Python字符串的长度。

ascii()

Python ascii()函数返回对象的字符串表示形式。 此函数在内部调用repr()函数,并在返回表示形式的字符串之前,使用\ x,\ u或\ U转义符对非ASCII字符进行转义。

bool()

Python bool()函数返回对象的布尔值。 bool类只有两个实例– True和False。

bytearray()

Python bytearray()函数返回一个bytearray对象,其中包含来自输入源的字节数组。

bytes()

此函数返回字节对象,该对象是不可变的整数序列,范围为0 <= x <256。

ord()

Python ord()函数采用单个Unicode字符的字符串参数,并返回其整数Unicode代码点值。

枚举()

Python枚举函数采用一个序列,然后将该序列的每个元素组成一个元组。

浮动()

顾名思义,python float()函数从输入参数中返回一个浮点数。

hash()

此函数返回给定对象的哈希值。

ID()

Python id()函数返回对象的“身份”。 一个对象的身份是一个整数,在该对象的生存期内,它保证是唯一且恒定的。

int()

Python int()函数从指定的输入返回一个整数对象。 返回的int对象将始终以10为底。

地图()

Python map()函数用于将函数应用于指定的iterable的所有元素,并返回map对象。

打印()

Python print()函数用于将数据打印到控制台中。

片()

Python slice()函数返回一个slice对象,该对象代表由range(start,stop,step)指定的一组索引。

类型()

此函数返回对象的类型。

(Useful String Operations)

  • f-string in Python – New and better way of formatting string introduced in Python 3.6. Python中的f-string – Python 3.6中引入的格式化字符串的新方法和更好的方法。
  • Substring in Python Python中的子字符串
  • Generate Random String 产生随机字串
  • Python string module Python字符串模块
  • Raw String 原始字符串
  • Multiline String 多行字符串
  • String Equality Check 字符串相等性检查
  • String Comparison 字符串比较
  • String Concatenation 字符串串联
  • String Slicing 字符串切片
  • Reverse a String 反转字符串
  • String to datetime – strptime() 字符串到日期时间– strptime()
  • Convert String to int 将String转换为int
  • Convert String to bytes 将字符串转换为字节
  • Convert String to float 将String转换为float
  • Convert List to String 将列表转换为字符串
  • String Template Class 字符串模板类
  • Check if variable is String? 检查变量是否为字符串?
  • Concatenate String and int 连接字符串和整数
  • Remove character from String 从字符串中删除字符
  • How to Append Strings 如何附加字符串
  • Find String in List 在列表中查找字符串
  • Remove spaces from String 从字符串中删除空格

(Do I need to remember all of them?)

Nobody can remember all of them. You can always find them in your IDE. Below image is from my PyCharm IDE builtins.py file.

没有人会记住所有这些。 您始终可以在IDE中找到它们。 下面的图片来自我的PyCharm IDE builtins.py文件。

Python String Functions – PyCharm

Python字符串函数– PyCharm

(Have I listed All the Python String Methods?)

I have listed almost all the important python string methods. However, some of them might have missed. This list is updated till Python 3.7. So any function coming up in later releases is not listed here, at least not right now. If you think that I have missed some important function, please respond in comments and I will add them too.

我列出了几乎所有重要的python字符串方法。 但是,其中一些可能已经错过了。 此列表将更新到Python 3.7。 因此,以后的版本中未列出任何功能,至少现在没有列出。 如果您认为我错过了一些重要功能,请在评论中回复,我也会添加它们。