一个字符串是一个字符序列。Python字符串字变量在双引号"
单引号'
中。 Python字符串是不可变的,因此它们不能被改变。例如:
my_string = 'Hello'
# my_string[1] = 'E', 字符串不可更改,不支持修改
注意: 字符串本身不可变,但字符串变量可以被重新赋值其他字符串。
创建字符串
"
双引号包裹'
单引号包裹"""
或'''
三个双引号或单引号包裹,支持多行字符串。
代码:
my_string = 'Hello'
my_string = "Hello"
my_string = "I' m a 'Geek'"
# 转义
my_string = 'I' m a "Geek"'
my_string = 'I' m a 'Geek''
print(my_string)
# 三引号
my_string = """Hello
World"""
print(my_string)
# 三引号可以换行
my_string = "Hello \
World"
print(my_string)
结果:
I' m a 'Geek'
Hello
World
Hello World
字符串的索引
字符串str
可以类似列表索引访问某个字符,如str[0]
但不能修改str[0]
。
代码:
my_string = "Hello World"
# 字符串中第一个字符
b = my_string[0]
print(b)
# 字符串中第二个到第三个字符
b = my_string[1:3] # 不包含第三个字符
print(b)
b = my_string[:5] # 从开始到第五个字符
print(b)
b = my_string[6:] # 从第六个字符到结束
print(b)
b = my_string[::2] # 从开始到结束,每两个字符
print(b)
b = my_string[::-1] # 倒序
print(b)
结果:
H
el
Hello
World
HloWrd
dlroW olleH
字符串的连接
通过+
将多个字符串简单连接,并返回新的字符串。
代码:
# 用+链接字符串
greeting = "Hello"
name = "Tom"
sentence = greeting + ' ' + name
print(sentence)
结果:
Hello Tom
字符串的迭代
类似列表遍历,通过for
循环可以遍历字符串。
代码:
# 迭代字符串
my_string = 'Hello'
for i in my_string:
print(i)
结果:
H
e
l
l
o
判断字符串中是否包含某个字符或子字符串
in
判断某个字符是否在字符串中。
代码:
if "e" in "Hello":
print("yes")
if "llo" in "Hello":
print("yes")
结果:
yes
yes
常用方法
代码:
my_string = " Hello World "
# 去除字符串中的空格
my_string = my_string.strip()
print(my_string)
# 字符串的长度
print(len(my_string))
# 字符串的大小写
print(my_string.upper())
print(my_string.lower())
# 判断字符串是否以某个字符开头或结尾
print("hello".startswith("he"))
print("hello".endswith("llo"))
# 找到第一个匹配的字符串的索引,如果没有匹配的字符串,返回-1
print("Hello".find("o"))
# 字符串中包含 字符/子字符串 的个数
print("Hello".count("e"))
# 字符串中替换某个字符串
# 注意:原字符串不变
message = "Hello World"
new_message = message.replace("World", "Universe")
print(new_message)
# 分割字符串
my_string = "how are you doing"
a = my_string.split() # default argument is " "
print(a)
my_string = "one,two,three"
a = my_string.split(",")
print(a)
# 链接列表元素变成一个字符串
my_list = ['How', 'are', 'you', 'doing']
a = ' '.join(my_list)
print(a)
结果:
Hello World
11
HELLO WORLD
hello world
True
True
4
1
Hello Universe
['how', 'are', 'you', 'doing']
['one', 'two', 'three']
How are you doing
字符串格式化
.format()方法 和 古老的%s格式化
代码:
# 用{}作为占位符
a = "Hello {0} and {1}".format("Bob", "Tom")
print(a)
# 可以不指定位置,对应变量即可
a = "Hello {} and {}".format("Bob", "Tom")
print(a)
a = "The integer value is {}".format(2)
print(a)
# 数字格式化
a = "The float value is {0:.3f}".format(2.1234)
print(a)
a = "The float value is {0:e}".format(2.1234)
print(a)
a = "The binary value is {0:b}".format(2)
print(a)
# 古老的格式化方法,使用%运算符
print("Hello %s and %s" % ("Bob", "Tom"))
val = 3.14159265359
print("The decimal value is %d" % val)
print("The float value is %f" % val)
print("The float value is %.2f" % val)
结果:
Hello Bob and Tom
Hello Bob and Tom
The integer value is 2
The float value is 2.123
The float value is 2.123400e+00
The binary value is 10
Hello Bob and Tom
The decimal value is 3
The float value is 3.141593
The float value is 3.14
f-Strings 现代化的字符串格式化
自从Python 3.6开始,f-strings就可以使用变量来替换字符串中的占位符。
name = "Eric"
age = 25
a = f"Hello, {
name}. You are {
age}."
print(a)
pi = 3.14159
a = f"Pi is {
pi:.3f}"
print(a)
# 允许使用表达式
a = f"The value is {
2 * 60}"
print(a)
# 格式化输出
a = f"The value is {
2 * 60:05d}"
print(a)
结果:
Hello, Eric. You are 25.
Pi is 3.142
The value is 120
The value is 00120
字符串的不可变性和连接
尽管字符串是不可变的,但是我们可以使用 +
或 +=
创建一个新字符串。 但是对于多个字符串的操作来说很费时,通常使用.join()
会快得多。
代码:
from timeit import default_timer as timer
my_list = ["a"] * 1000000
# 差的
start = timer()
a = ""
for i in my_list:
a += i
end = timer()
print("concatenate string with + : %.5f" % (end - start))
# 快的
start = timer()
a = "".join(my_list)
end = timer()
print("concatenate string with join(): %.5f" % (end - start))
结果:
concatenate string with + : 0.13190
concatenate string with join(): 0.00566
小节
字符串是编程中不可缺失的数据类型,掌握好字符串的特性及常用方法,可将很多事情事半功倍!
如果觉得有所收获,欢迎大家点赞、首次、支持!
pythontip 出品,Happy Coding!
公众号: 夸克编程