Python字符串


字符串

python 中的字符串文本由单个引号或双引号包围。

“你好"和’你好’是一样的。

您可以使用 以下函数显示字符串文本:print()

例子

 print("Hello")
print('Hello')

将字符串分配给变量

将字符串分配给变量使用变量名称后跟一个等号和字符串完成:

例子

 a = "Hello"
print(a)

多行字符串

可以使用三个引号将多行字符串分配给变量:

例子

您可以使用三个双引号:

 a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

或三个单引号:

例子

 a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

**注意:**在结果中,换行符插入的位置与代码中的位置相同。



字符串是数组

与许多其他流行的编程语言一样,Python 中的字符串是表示单码字符的字节数组。

但是,Python 没有字符数据类型,单个字符只是长度为 1 的字符串。

方括号可用于访问字符串的元素。

例子

获取位置 1 的字符(请记住,第一个字符具有位置 0):

 a = "Hello, World!"
print(a[1])

切片

可以使用切片语法返回字符范围。

指定开始索引和结束索引(由冒号分隔)以返回字符串的一部分。

例子

获取字符从位置 2 到位置 5(不包括):

 b = "Hello, World!"
print(b[2:5])

负索引

使用负索引从字符串末尾开始切片:

例子

获取从位置 5 到位置 1(不包括)的字符,从字符串末尾开始计数:

 b = "Hello, World!"
print(b[-5:-2])

字符串长度

若要获取字符串的长度,请使用 函数。len()

例子

函数返回字符串的长度:len()

 a = "Hello, World!"
print(len(a))

字符串方法

Python 有一组内置方法,可用于字符串。

例子

该方法从开头或末尾删除任何空白:strip()

 a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"

例子

该方法以小写返回字符串:lower()

 a = "Hello, World!"
print(a.lower())

例子

该方法返回大写字符串:upper()

 a = "Hello, World!"
print(a.upper())

例子

方法将字符串替换为另一个字符串:replace()

 a = "Hello, World!"
print(a.replace("H", "J"))

例子

如果该方法找到分隔符的实例,则将字符串拆分为子字符串:split()

 a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']

使用字符串方法参考了解有关字符串方法的详细了解


检查字符串

要检查字符串中是否存在某个短语或字符,可以使用关键字或 。in``````not in

例子

检查以下文本中是否存在短语"ain”:

 txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)

例子

检查以下文本中是否不存在短语"ain":

 txt = "The rain in Spain stays mainly in the plain"
x = "ain" not in txt
print(x) 

字符串串联

若要连接或组合两个字符串,可以使用 + 运算符。

例子

将变量与变量合并为变量 :a``````b``````c

 a = "Hello"
b = "World"
c = a + b
print(c)

例子

若要在它们之间添加空格,请添加 :" "

 a = "Hello"
b = "World"
c = a + " " + b
print(c)

字符串格式

正如我们在 Python 变量章节中学到的,我们不能像这样组合字符串和数字:

例子

 age = 36
txt = "My name is John, I am " + age
print(txt)

但是,我们可以通过使用 方法组合字符串和数字!format()

该方法采用传递的参数,设置它们格式,并将它们放在占位符的字符串中:format()``````{}

例子

使用 方法将数字插入字符串中:format()

 age = 36
txt = "My name is John, and I am {}"
print(txt.format(age))

format() 方法采用无限数量的参数,并放置在相应的占位符中:

例子

 quantity = 3
itemno = 567
price = 49.95
myorder = "I want {} pieces of item {} for {} dollars."
print(myorder.format(quantity, itemno, price))

您可以使用索引号确保参数放置在正确的占位符中:{0}

例子

 quantity = 3
itemno = 567
price = 49.95
myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
print(myorder.format(quantity, itemno, price))

转义字符

若要在字符串中插入非法字符,请使用转义字符。

转义字符是反斜杠,后跟要插入的字符。\

非法字符的示例是字符串内的双引号,该字符串由双引号包围:

例子

如果在字符串内使用双引号,则出现错误:使用双引号:

 txt = "We are the so-called "Vikings" from the north."

To fix this problem, use the escape character :\"

Example

The escape character allows you to use double quotes when you normally would not be allowed:

 txt = "We are the so-called \"Vikings\" from the north."

Python 中使用的其他转义字符:

| Code | Result | | ' | Single Quote | | \ | Backslash | | \n | New Line | | \r | Carriage Return | | \t | Tab | | \b | Backspace | | \f | Form Feed | | | \ooo | Octal value | | \xhh | Hex value |


字符串方法

Python 有一组内置方法,可用于字符串。

**注:**所有字符串方法都返回新值。它们不会更改原始字符串。

| Method | Description | | capitalize() | Converts the first character to upper case | | casefold() | Converts string into lower case | | center() | Returns a centered string | | count() | Returns the number of times a specified value occurs in a string | | encode() | Returns an encoded version of the string | | endswith() | Returns true if the string ends with the specified value | | expandtabs() | Sets the tab size of the string | | find() | Searches the string for a specified value and returns the position of where it was found | | format() | Formats specified values in a string | | format_map() | Formats specified values in a string | | index() | Searches the string for a specified value and returns the position of where it was found | | isalnum() | Returns True if all characters in the string are alphanumeric | | isalpha() | Returns True if all characters in the string are in the alphabet | | isdecimal() | Returns True if all characters in the string are decimals | | isdigit() | Returns True if all characters in the string are digits | | isidentifier() | Returns True if the string is an identifier | | islower() | Returns True if all characters in the string are lower case | | isnumeric() | Returns True if all characters in the string are numeric | | isprintable() | Returns True if all characters in the string are printable | | isspace() | Returns True if all characters in the string are whitespaces | | istitle() | Returns True if the string follows the rules of a title | | isupper() | Returns True if all characters in the string are upper case | | join() | Joins the elements of an iterable to the end of the string | | ljust() | Returns a left justified version of the string | | lower() | Converts a string into lower case | | lstrip() | Returns a left trim version of the string | | maketrans() | Returns a translation table to be used in translations | | partition() | Returns a tuple where the string is parted into three parts | | replace() | Returns a string where a specified value is replaced with a specified value | | rfind() | Searches the string for a specified value and returns the last position of where it was found | | rindex() | Searches the string for a specified value and returns the last position of where it was found | | rjust() | Returns a right justified version of the string | | rpartition() | Returns a tuple where the string is parted into three parts | | rsplit() | Splits the string at the specified separator, and returns a list | | rstrip() | Returns a right trim version of the string | | split() | Splits the string at the specified separator, and returns a list | | splitlines() | Splits the string at line breaks and returns a list | | startswith() | Returns true if the string starts with the specified value | | strip() | Returns a trimmed version of the string | | swapcase() | Swaps cases, lower case becomes upper case and vice versa | | title() | Converts the first character of each word to upper case | | translate() | Returns a translated string | | upper() | Converts a string into upper case | | zfill() | Fills the string with a specified number of 0 values at the beginning |