网站首页 > 知识剖析 正文
字符串连接
将字符串连接起来:
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)
猜你喜欢
- 2025-03-25 Python中的切片slice操作(python的切片规则)
- 2025-03-25 golang string不能修改(golang strings)
- 2025-03-25 .NET零拷贝实现大String编码到多个非连续内存块中
- 2025-03-25 javascript string 巩固学习整理 (二)
- 2025-03-25 Rust中的字符串String和&str的区别和应用场景
- 2025-03-25 你必须知道的 7 个杀手级 JavaScript 单行代码
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)