字符串连接
将字符串连接起来:
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name + "!"
print(message)
2. 使用str.format进行字符串格式化
将值插入到字符串模板中:
message = "{}, {}. Welcome!".format(greeting, name)
print(message)
3. 格式化字符串字面量(f-字符串)
在字符串字面量内嵌入表达式(Python 3.6+):
message = f"{greeting}, {name}. Welcome!"
print(message)
4. 字符串方法 — 大小写转换
将字符串的大小写进行更改:
s = "Python"
print(s.upper()) # Uppercase
print(s.lower()) # Lowercase
print(s.title()) # Title Case
5. 字符串方法 —strip、rstrip、lstrip
删除字符串两端空白或特定字符:
s = " trim me "
print(s.strip()) # Both ends
print(s.rstrip()) # Right end
print(s.lstrip()) # Left end
6. 字符串方法 —startswith、endswith
检查字符串的开始或结束位置是否存在特定文本:
s = "filename.txt"
print(s.startswith("file")) # True
print(s.endswith(".txt")) # True
7. 字符串方法 —split、join
将字符串拆分为列表或将列表连接成字符串:
s = "split,this,string"
words = s.split(",") # Split string into list
joined = " ".join(words) # Join list into string
print(words)
print(joined)
8. 字符串方法 —replace
将字符串的一部分替换为另一个字符串:
s = "Hello world"
new_s = s.replace("world", "Python")
print(new_s)
9. 字符串方法 —find、index
要查找子字符串在字符串中的位置:
s = "look for a substring"
position = s.find("substring") # Returns -1 if not found
index = s.index("substring") # Raises ValueError if not found
print(position)
print(index)
10. 字符串方法 — 处理字符
处理字符串中的单个字符:
s = "characters"
for char in s:
print(char) # Prints each character on a new line
11. 字符串方法 —isdigit、isalpha、isalnum
检查一个字符串是否只包含数字、字母或字母数字字符:
print("123".isdigit()) # True
print("abc".isalpha()) # True
print("abc123".isalnum())# True
12. 字符串切片
使用切片提取子字符串:
s = "slice me"
sub = s[2:7] # From 3rd to 7th character
print(sub)
13. 字符串长度使用len
获取字符串长度:
s = "length"
print(len(s)) # 6
14. 多行字符串
与跨越多行的字符串一起工作:
multi = """Line one
Line two
Line three"""
print(multi)
15. 原始字符串
将反斜杠视为字面字符,这在正则表达式模式和文件路径中很有用:
path = r"C:\User\name\folder"
print(path)