字符串
创建
python
# 使用单引号
str1 = '你好,世界!'
# 使用双引号
str2 = "Hello, World!"
# 当字符串本身包含单引号时,可以使用双引号创建
str3 = "It's a beautiful day."
# 当字符串本身包含双引号时,可以使用单引号创建
str4 = 'He said, "Python is fun!"'
# 使用三单或双引号创建多行字符串(换行也会被保留)
multi_line_str1 = '''这是一个
包含多行的
字符串。'''
multi_line_str2 = """This is also
a multi-line
string."""
print(str1)
print(str2)
print(str3)
print(str4)
print(multi_line_str1)
print(multi_line_str2)
Python 中的字符串是不可变序列。这意味着一旦字符串被创建,它的内容就不能被直接修改。对字符串的任何操作(如替换、拼接等)都会返回一个 新的 字符串对象,而原始字符串保持不变。
基本操作
访问
- [index]
- 注意逆向从
-1
开始,正向从0
开始
python
str2 = "Hello, World!"
print(str2[0]) # H
print(str2[1]) # e
print(str2[-1]) # !
print(str2[-2]) # d
切片
string[start:stop:step]
start
: 起始索引(包含),默认为 0。stop
: 结束索引(不包含),默认为字符串长度。step
: 步长(每次跳跃的字符数),默认为 1。注意逆向从
-1
开始,正向从0
开始,右边不包含
python
str2 = "Hello,World"
# 默认值,打印所有,即[0:len(str2):1]
print(str2)
print(str2[:])
print(str2[::])
# 输出字符串中的前5个字符, 步长为2
print(str2[:5:2]) # Hlo
# 输出字符串中的最后5个字符, 步长为2
print(str2[-5:0:-2]) # Wol
# 反转字符串
print(str2) # 原字符串,Hello,World
str2 = str2[::-1]
print(str2) # dlroW,olleH
拼接
+
用于拼接两个字符串
python
str1 = "Hello"
str2 = "World"
result = str1 + ", " + str2 + "!"
print("输出是:" + result) # 输出是:Hello, World!
num1 = 10
str3 = "num1是"
print(str3 + str(num1)) # num1是10
字符串重复
*
可以重复多次字符串
python
line = "-" * 20
print(line) # 输出: --------------------
word = "Ha" * 3
print(word) # 输出: HaHaHa
成员检查
in
和not in
python
text = "Python programming is fun."
print("Python" in text) # 输出: True
print("Java" in text) # 输出: False
print("fun." not in text) # 输出: False
长度
len方法实际可作用于list、tuple等
python
md = "this is"
print(len(md)) # 7
大小写方法
lower()
: 返回字符串的小写副本。upper()
: 返回字符串的大写副本。title()
: 返回字符串的副本,每个单词的首字母大写。swapcase()
: 返回字符串的副本,大小写互换。
python
text = "pyThoN PRograMMing"
print(text.lower()) # 输出: python programming
print(text.upper()) # 输出: PYTHON PROGRAMMING
print(text.title()) # 输出: Python Programming
print(text.swapcase()) # 输出: PYtHOn prOGRAmmiNG
print(text) # 输出:原始字符串
去除空白
python
md = " this is "
strip = md.strip()
print(strip) # "this is"
查找替换
python
sentence = "this is a test sentence, this is simple."
print(sentence.find("is")) # 输出: 2 (第一次出现 'is' 的索引)
print(sentence.find("is", 3)) # 输出: 5 (从索引 3 开始查找第一次出现 'is' 的索引)
print(sentence.find("Python")) # 输出: -1 ('Python' 不存在)
print(sentence.rfind("is")) # 输出: 28 (最后一次出现 'is' 的索引)
print(sentence.count("is")) # 输出: 3 ('is' 出现了 3 次)
print(
sentence.replace("is", "was")) # 输出: thwas was a test sentence, thwas was simple. (所有 'is' 被替换)
print(sentence.replace("is", "was",
2)) # 输出: thwas was a test sentence, this is simple. (只替换前 2 个 'is')
print(sentence.startswith("this")) # 输出: True
print(sentence.endswith("simple.")) # 输出: True
格式化输出
在字符串前加上
f
,然后用{}
包裹变量名或表达式
python
name = "Alice"
age = 30
height = 1.65
# My name is Alice and I am 30 years old.
print(f"My name is {name} and I am {age} years old.")
# :.2f 表示保留两位小数的浮点数
print(f"My height is {height:.2f} meters.") # 输出: My height is 1.65 meters.
原始字符串
如果在字符串前加上
r
或R
,那么字符串中的反斜杠 \
将不再被解释为转义字符,而是按原样保留。
python
# 原始字符串,否则\n会转义,出错
path2 = r"C:\Users\new_folder"
print(path2) # 输出: C:\Users\new_folder