Python 字符串
字符串
Python 中的字符串可以用单引号或双引号括起来。
'hello' 和 "hello" 是相同的。
您可以使用 print()
函数显示字符串字面量
引号中的引号
你可以在字符串中使用引号,只要它们不与包围字符串的引号匹配
为变量赋字符串值
将字符串赋给变量,变量名后跟等号,然后是字符串。
多行字符串
您可以使用三个引号来为变量赋值多行字符串
示例
您可以使用三个双引号
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 中的字符串是表示 Unicode 字符的字节数组。
但是,Python 没有字符数据类型,单个字符只是一个长度为 1 的字符串。
可以使用方括号访问字符串的元素。
遍历字符串
由于字符串是数组,我们可以通过 for
循环遍历字符串中的字符。
在我们的 Python For Loops 章节中了解更多关于 For Loops 的信息。
字符串长度
要获取字符串的长度,请使用 len()
函数。
检查字符串
要检查某个短语或字符是否存在于字符串中,我们可以使用关键字 in
。
在 if
语句中使用它
示例
仅当“free”存在时打印
txt = "The best things in life are free!"
if "free" in txt
print("Yes, 'free' is present.")
自己动手试一试 »
在我们的 Python If...Else 章节中了解更多关于 If 语句的信息。
检查是否不存在
要检查某个短语或字符是否不在字符串中,我们可以使用关键字 not in
。
示例
检查“expensive”是否不存在于以下文本中
txt = "The best things in life are free!"
print("expensive" not in txt)
自己动手试一试 »
在 if
语句中使用它
示例
仅当“expensive”不存在时打印
txt = "The best things in life are free!"
if "expensive" not in txt
print("No, 'expensive' is NOT present.")
自己动手试一试 »