Python 字符串
Python 字符串
字符串
在 Python 中,字符串由单引号或双引号包围。
'hello' 与 "hello" 是相同的。
你可以使用 [print()] 函数显示字符串字面值:
示例
print("Hello")
print('Hello')
嵌套引号
你可以在字符串中使用引号,只要它们与包围字符串的引号不匹配:
示例
print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')
将字符串分配给一个变量
将字符串赋值给变量是通过变量名后跟等号和字符串来完成的:
示例
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中的字符串是unicode字符的数组。
然而,Python 并没有字符数据类型,单个字符只是一个长度为 1 的字符串。
方括号可以用来访问字符串的元素。
示例
获取位置为1的字符(请记住,第一个字符的位置是0):
a = "Hello, World!"
print(a[1])
遍历字符串
由于字符串是数组,我们可以使用[for](https://www.w3schools.com/python/ref_keyword_for.asp)循环来遍历字符串中的字符。
示例
循环遍历单词 "banana" 中的字母:
for x in "banana":
print(x)
了解更多关于我们的[Python For Loops]章节中的For Loops内容。
字符串长度
要获取字符串的长度,请使用 [len()](https://www.w3schools.com/python/ref_func_len.asp) 函数。
示例
该[len()]函数返回字符串的长度:
a = "Hello, World!"
print(len(a))
检查字符串
要检查字符串中是否包含某个短语或字符,我们可以使用关键字 [in](https://www.w3schools.com/python/ref_keyword_in.asp).
示例
检查以下文本中是否包含“free”:
txt = "The best things in life are free!"
print("free" in txt)
在 [if] 语句中使用它:
示例
仅在“free”存在时打印:
txt = "The best things in life are free!"
if "free" in txt:
print("Yes, 'free' is present.")
在我们的Python章节中了解更多关于If语句的信息。
检查是否不是
要检查字符串中是否不包含某个短语或字符,我们可以使用关键字[not in].
示例
检查以下文本中是否没有出现“昂贵”:
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.")
