pythonstr 内置函数
时间: 2025-05-21 16:47:50 浏览: 16
### Python 字符串内置函数及其用法
以下是 Python 中常用的字符串内置函数以及其具体功能和用法:
#### 1. `find()` 函数
`find()` 方法用于查找子字符串在原字符串中的位置。如果找到,则返回第一个匹配项的索引;如果没有找到,则返回 `-1`。
```python
s = "hello world"
result = s.find("world") # 返回 6 表示从第6位开始有匹配[^1]
```
#### 2. `index()` 函数
`index()` 类似于 `find()`,但它会在找不到子字符串时抛出异常而不是返回 `-1`。
```python
s = "hello world"
try:
result = s.index("world") # 找到则返回索引值 6
except ValueError:
print("Substring not found")
```
#### 3. `split()` 函数
`split()` 将字符串按照指定分隔符拆分成多个部分并返回一个列表。
```python
text = "apple,banana,cherry"
fruits = text.split(",") # ['apple', 'banana', 'cherry'][^1]
```
#### 4. `join()` 函数
`join()` 用于将序列中的元素以指定字符连接成一个新的字符串。
```python
words = ["hello", "world"]
sentence = " ".join(words) # 输出 "hello world"
```
#### 5. `replace()` 函数
`replace()` 替换字符串中所有的旧子字符串为新子字符串。
```python
message = "hello world"
new_message = message.replace("world", "Python") # hello Python
```
#### 6. `isdigit()` 函数
`isdigit()` 判断字符串是否只由数字组成。
```python
num_str = "12345"
print(num_str.isdigit()) # True
```
#### 7. `isalpha()` 函数
`isalpha()` 检查字符串是否仅包含字母。
```python
alpha_str = "abcXYZ"
print(alpha_str.isalpha()) # True
```
#### 8. `isspace()` 函数
`isspace()` 验证字符串是否全部为空白字符(如空格、制表符等)。
```python
space_str = " "
print(space_str.isspace()) # True
```
#### 9. `strip()` 函数
`strip()` 移除字符串两端的空白字符或其他指定字符。
```python
str_with_spaces = " Hello World! "
cleaned_str = str_with_spaces.strip() # "Hello World!"
```
#### 10. `count()` 函数
`count()` 统计某个子字符串在原始字符串中出现的次数。
```python
phrase = "how much wood would a woodchuck chuck"
word_count = phrase.count("wood") # 2
```
#### 11. `len()` 函数
虽然严格来说不是字符串的方法,但它是用来获取字符串长度的标准方式。
```python
string_length = len("example") # 7
```
#### 12. `startswith()` 和 `endswith()` 函数
这两个方法分别验证字符串是否以特定前缀或后缀开头/结尾。
```python
url = "https://www.example.com"
print(url.startswith("https")) # True
print(url.endswith(".com")) # True
```
#### 13. `upper()` 和 `lower()` 函数
转换整个字符串为大写或小写字母形式。
```python
name = "Alice"
uppercase_name = name.upper() # ALICE
lowercase_name = uppercase_name.lower() # alice
```
#### 14. 映射替换 (`maketrans()` 和 `translate()`)
可以通过创建翻译表来实现更复杂的字符替换操作。
```python
trans_table = str.maketrans('abcdefg', '1234567')
translated_text = "abc".translate(trans_table) # "123"[^2]
```
#### 15. 动态调用函数 (通过名称)
利用 `globals()` 或者 `locals()` 可以动态执行对应名字的函数。
```python
def add(a, b): return a + b
func_name = "add"
dynamic_func_call = globals()[func_name](1, 2) # 结果为 3[^3]
```
---
阅读全文
相关推荐
















