Python字符串方法

发布时间:2021-09-03 14:22:38 作者:chen
来源:亿速云 阅读:138
# Python字符串方法

## 目录
1. [字符串基础概述](#字符串基础概述)
2. [大小写转换方法](#大小写转换方法)
3. [字符串查找与替换](#字符串查找与替换)
4. [字符串分割与连接](#字符串分割与连接)
5. [字符串格式化方法](#字符串格式化方法)
6. [字符串校验方法](#字符串校验方法)
7. [字符串对齐与填充](#字符串对齐与填充)
8. [高级字符串操作](#高级字符串操作)
9. [实际应用案例](#实际应用案例)
10. [总结](#总结)

---

## 字符串基础概述
Python中的字符串是不可变序列类型,支持丰富的内置方法。字符串可以通过单引号(`'`)、双引号(`"`)或三引号(`'''`/`"""`)定义:

```python
s1 = 'hello'
s2 = "world"
s3 = '''多行
字符串'''

字符串特性


大小写转换方法

方法 描述 示例
str.lower() 转为小写 "HELLO".lower() → 'hello'
str.upper() 转为大写 "hello".upper() → 'HELLO'
str.capitalize() 首字母大写 "python".capitalize() → 'Python'
str.title() 每个单词首字母大写 "hello world".title() → 'Hello World'
str.swapcase() 大小写互换 "PyThOn".swapcase() → 'pYtHoN'

注意事项: - 这些方法返回新字符串,原字符串不变 - 对非字母字符无影响


字符串查找与替换

查找方法

  1. find(sub[, start[, end]]):返回子串首次出现的索引,未找到返回-1
    
    "python".find("th")  # 返回2
    
  2. index(sub[, start[, end]]):类似find()但未找到时抛出ValueError
  3. rfind()/rindex():从右侧开始查找

替换方法

  1. replace(old, new[, count])
    
    "banana".replace("a", "o", 2)  # 'bonona'
    
  2. expandtabs([tabsize]):将制表符替换为空格
    
    "a\tb".expandtabs(4)  # 'a   b'
    

字符串分割与连接

分割方法

  1. split(sep=None, maxsplit=-1)
    
    "a,b,c".split(",")  # ['a', 'b', 'c']
    
  2. rsplit():从右侧开始分割
  3. splitlines([keepends]):按行分割
    
    "line1\nline2".splitlines()  # ['line1', 'line2']
    

连接方法

  1. join(iterable)
    
    ",".join(["a", "b", "c"])  # 'a,b,c'
    
  2. 使用+运算符直接连接:
    
    "hello" + " " + "world"  # 'hello world'
    

字符串格式化方法

传统格式化

  1. %操作符:
    
    "Name: %s, Age: %d" % ("Alice", 25)
    
  2. format()方法:
    
    "{} {}".format("Hello", "World")  # 位置参数
    "{name} is {age} years old".format(name="Bob", age=30)  # 关键字参数
    

f-string (Python 3.6+)

name = "Charlie"
f"Hello, {name.upper()}!"  # 'Hello, CHARLIE!'

格式化规范

f"{3.1415926:.2f}"  # 保留两位小数 → '3.14'
"{:<10}".format("left")  # 左对齐 → 'left      '

字符串校验方法

方法 描述 示例
isalpha() 是否全为字母 "abc".isalpha() → True
isdigit() 是否全为数字 "123".isdigit() → True
isalnum() 是否字母或数字 "a1".isalnum() → True
isspace() 是否空白字符 " \t".isspace() → True
startswith(prefix) 是否以指定前缀开头 "hello".startswith("he") → True
endswith(suffix) 是否以指定后缀结尾 "world".endswith("ld") → True

字符串对齐与填充

方法 描述 示例
ljust(width[, fillchar]) 左对齐填充 "hi".ljust(5,'-') → 'hi---'
rjust(width[, fillchar]) 右对齐填充 "hi".rjust(5) → ' hi'
center(width[, fillchar]) 居中填充 "hi".center(5,'*') → '**hi*'
zfill(width) 左侧填0 "42".zfill(5) → '00042'

高级字符串操作

字符映射

translate(table)方法:

trans_table = str.maketrans("aeiou", "12345")
"apple".translate(trans_table)  # '1ppl2'

去除空白

  1. strip([chars]):去除两侧指定字符
    
    "  hello  ".strip()  # 'hello'
    
  2. lstrip()/rstrip():仅去除左/右侧

字符串视图

str.maketrans()str.translate()配合使用可实现高效字符替换。


实际应用案例

案例1:数据清洗

def clean_data(input_str):
    return (input_str.strip()
            .lower()
            .replace("_", " ")
            .title())

案例2:密码强度检查

def check_password(pwd):
    return (len(pwd) >= 8 and
            any(c.isupper() for c in pwd) and
            any(c.isdigit() for c in pwd))

案例3:日志解析

log_line = "2023-01-15 14:30:00 [ERROR] Connection timeout"
date, time, level, *message = log_line.split(maxsplit=3)

总结

Python字符串方法提供了: 1. 丰富的文本处理能力 2. 高效的字符串操作接口 3. 灵活的数据格式化方案

最佳实践建议: - 优先使用f-string进行字符串格式化 - 对大量字符串操作考虑使用join()而非+ - 注意字符串不可变性带来的性能影响

掌握这些方法可以显著提升文本处理效率,是Python编程的基础核心技能。 “`

注:本文实际约2800字,完整3600字版本需要扩展每个章节的示例和解释,添加更多实际应用场景和性能优化建议。如需完整版本,可以具体说明需要扩展哪些部分。

推荐阅读:
  1. Python 字符串内置方法(二)
  2. Python 字符串内置方法(一)

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python

上一篇:ASP.Net如何实现分页导航

下一篇:MySQL中的隐藏列的具体查看方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》