Python 字符串操作基础应用

Python 字符串操作:拼接、格式化与常见字符串方法

在 Python 编程中,字符串是最常用的数据类型之一。直接开始吧!


一、字符串的拼接与格式化

1.1 使用 + 拼接字符串

+ 操作符将两个或多个字符串连接成一个新字符串。

str1 = "你好"
str2 = "世界"
result = str1 + "," + str2 + "!"
print(result)

输出:

你好,世界!

1.2 使用 f-string 格式化字符串

f-string 是 Python 3.6 引入的一种简洁的字符串格式化方法,可以将变量直接嵌入到字符串中。

name = "小明"
age = 18
message = f"大家好,我叫{name},今年{age}岁。"
print(message)

输出:

大家好,我叫小明,今年18岁。

小提示:

  • f 字符串中,可以直接嵌入表达式,如 f"{1 + 2}"

  • 1.3 使用 format() 方法

    format() 是 Python 提供的另一种格式化字符串的方法。

    fruit = "苹果"
    quantity = 10
    result = "我买了{}个{}。".format(quantity, fruit)
    print(result)
    

    输出:

    我买了10个苹果。
    

    二、常见字符串方法

    2.1 strip():去除首尾空格或指定字符

    strip() 方法可以去除字符串开头和结尾的空格或指定字符。

    text = "  你好,世界  "
    clean_text = text.strip()
    print(f"'{clean_text}'")
    

    输出:

    '你好,世界'
    

    示例: 去除指定字符

    text = "###详情摘要###"
    clean_text = text.strip("#")
    print(clean_text)
    

    输出:

    详情摘要
    

    2.2 lower()upper():大小写转换

  • lower() 将字符串中的字母全部转换为小写。
  • upper() 将字符串中的字母全部转换为大写。
  • text = "Hello World"
    print(text.lower())  # 输出:hello world
    print(text.upper())  # 输出:HELLO WORLD
    

    2.3 split():拆分字符串

    split() 方法根据指定的分隔符将字符串拆分成列表。如果不指定分隔符,默认以空格拆分。

    sentence = "学习 Python 编程"
    words = sentence.split()
    print(words)
    

    输出:

    ['学习', 'Python', '编程']
    

    示例: 使用逗号作为分隔符

    data = "苹果,香蕉,鸭梨"
    fruits = data.split(",")
    print(fruits)
    

    输出:

    ['苹果', '香蕉', '鸭梨']
    

    三、完整示例:字符串处理综合应用

    下面是一个综合示例,演示如何使用字符串拼接、格式化和常见方法:

    name = "张三"
    hobby = " 写代码 "
    message = f"大家好,我是{name}。我的爱好是{hobby.strip()}。"
    print(message)
    
    items = "手机,电脑,耳机"
    item_list = items.split(",")
    print(f"我想买:{item_list}")
    

    输出:

    大家好,我是张三。我的爱好是写代码。
    我想买:['手机', '电脑', '耳机']
    

    四、更多字符串方法与技巧

    除了上面介绍的常用字符串操作,Python 还提供了许多其他有用的方法。下面介绍一些更进阶但常见的字符串操作:


    4.1 replace():替换字符串中的内容

    replace() 方法可以将字符串中的某部分替换为指定的新内容。

    text = "我喜欢苹果"
    new_text = text.replace("苹果", "香蕉")
    print(new_text)
    

    输出:

    我喜欢香蕉
    

    应用场景:

  • 处理用户输入时,将敏感词替换为“*”。
  • 替换内容,如将占位符替换文字。
  • 将某内容批量替换为另一个内容。

  • 4.2 join():将列表元素拼接成字符串

    join() 方法用于将一个列表中的元素通过指定分隔符连接为一个字符串。 Example: ‘.’.join([‘a’, ‘b’, ‘c’]) -> ‘a.b.c’

    words = ["PY", "世界", "第一"]
    sentence = " ".join(words)
    print(sentence)
    

    输出:

    PY 世界 第一
    

    示例: 使用逗号分隔

    fruits = ["苹果", "香蕉", "梨"]
    result = ",".join(fruits)
    print(result)
    

    输出:

    苹果,香蕉,梨
    

    4.3 startswith()endswith():检测字符串的开头和结尾

  • startswith() 检查字符串是否以指定的内容开头。
  • endswith() 检查字符串是否以指定的内容结尾。
  • filename = "looklook.png"
    print(filename.startswith("looklook"))  # 输出:True
    print(filename.endswith(".pdf"))      # 输出:False
    

    应用场景:

  • 判断文件类型或路径。
  • 检查网址是否以指定的协议(如 http://)开头。

  • 4.4 find():查找子字符串的位置

    find() 方法返回指定子字符串在字符串中的首次出现位置,找不到则返回 -1

    text = "我喜欢学习Python"
    position = text.find("Python")
    print(position)
    

    输出:

    5
    

    应用场景:

  • 判断某个关键词是否存在于用户输入中。
  • 查找特定内容的索引位置用于进一步处理。

  • 4.5 count():统计子字符串出现的次数

    count() 用于统计某个子字符串在字符串中出现的次数。

    text = "香蕉苹果香蕉梨香蕉"
    banana_count = text.count("香蕉")
    print(f"香蕉出现了{banana_count}次")
    

    输出:

    香蕉出现了3次
    

    五、字符串编码与解码(encode()decode()

    在处理网络传输或文件读写时,可能需要对字符串进行编码或解码。

  • encode():将字符串转换为指定编码的字节序列。
  • decode():将字节序列解码为字符串。
  • text = "你好"
    encoded_text = text.encode("utf-8")
    print(encoded_text)  # 输出:b'\xe4\xbd\xa0\xe5\xa5\xbd'
    print(type(encoded_text)) # 输出: <class 'bytes'>
    
    decoded_text = encoded_text.decode("utf-8")
    print(decoded_text)  # 输出:你好
    

    应用场景:

  • 网络请求时,将字符串转换为字节流。
  • 处理文件时确保编码格式一致,避免乱码。

  • 六、进行 URL 编码

    6.1 使用quote()函数进行 URL 编码

    from urllib.parse import quote
    
    string = "Hello World! 你好,世界!"
    encoded_string = quote(string)
    print(encoded_string)
    

    输出:

    Hello%20World%21%20%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C%EF%BC%81
    

    6.2 使用quote_plus()函数进行 URL 编码(类似于quote()但对空格编码为+)

    from urllib.parse import quote_plus
    
    string = "Hello World! 你好,世界!"
    encoded_string = quote_plus(string)
    print(encoded_string)
    

    输出:

    Hello+World%21+%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C%EF%BC%81
    

    6.3 对 URL 的参数部分进行编码可以使用urlencode()函数

    from urllib.parse import urlencode
    
    params = {'name': '张三', 'age': '15'}
    encoded_params = urlencode(params)
    print(encoded_params)
    

    输出:

    name=%E5%BC%A0%E4%B8%89&age=15
    

    6.4 解码操作

    6.4.1 使用unquote()函数进行解码 (针对quote解码)

    urllib.parse模块的unquote()函数用于将经过 URL 编码的字符串进行解码。识别以%开头的十六进制编码部分,并将其转换回原始字符。对于+这种保持原样。

    from urllib.parse import unquote
    encoded_str = "Hello%20World%21%20%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C%EF%BC%81"
    decoded_str = unquote(encoded_str)
    print(decoded_str) # 输出: Hello World! 你好,世界!
    
    6.4.2 使用unquote_plus()函数进行解码(针对quote_plus()编码的字符串)

    unquote_plus()函数用于解码由quote_plus()编码的字符串。它不仅会将%开头的十六进制编码转换回原始字符,还会将+号转换为空格。

    from urllib.parse import unquote_plus
    encoded_str = "Hello+World%21+%E4%BD%A0%E5%A5%BD%EF%BC%8C%E4%B8%96%E7%95%8C%EF%BC%81"
    decoded_str = unquote_plus(encoded_str)
    print(decoded_str) # 输出: Hello World! 你好,世界!
    
    6.4.3 处理 URL 参数解码场景下的应用
    from urllib.parse import unquote_plus
    url_params_str = "name=%E5%BC%A0+%E4%B8%89&age=15"
    params_list = url_params_str.split("&") # 分割 & 参数
    decoded_params = {}
    for param in params_list:
        key_value = param.split("=") # 分割 健=值
        if len(key_value) == 2: # 解码并填充字典⬇️
            decoded_params[unquote_plus(key_value[0])] = unquote_plus(key_value[1])
    print(decoded_params)
    

    输出:

    {'name': '张 三', 'age': '15'}
    

    七、处理多行字符串('''"""

    在某些情况下,我们需要处理多行字符串,例如输出诗句或文章段落。Python 支持用 三引号'''""")来定义多行字符串。

    text = """静夜思
    床前明月光,
    疑是地上霜。
    举头望明月,
    低头思故乡。"""
    print(text)
    

    输出:

    静夜思
    床前明月光,
    疑是地上霜。
    举头望明月,
    低头思故乡。
    

    八、总结

    每天学一学、天天好心情!

    Python 字符串处理函数列表

    第一部分

    函数名 说明 使用示范
    str.lower() 将字符串中的所有字母转换为小写字母。 "Hello".lower()'hello'
    str.upper() 将字符串中的所有字母转换为大写字母。 "hello".upper()'HELLO'
    str.capitalize() 将字符串的首字母大写,其他字母小写。 "hello world".capitalize()'Hello world'
    str.title() 将每个单词的首字母大写。 "hello world".title()'Hello World'
    str.strip() 去除字符串开头和结尾的空白字符。 " hello ".strip()'hello'
    str.lstrip() 去除字符串左侧的空白字符。 " hello".lstrip()'hello'
    str.rstrip() 去除字符串右侧的空白字符。 "hello ".rstrip()'hello'
    str.replace() 替换字符串中的指定子串。 "apple".replace('a', 'o')'opple'
    str.split() 按指定分隔符拆分字符串为列表。 "a,b,c".split(',')['a', 'b', 'c']
    str.join() 用指定的字符串连接列表中的元素。 " ".join(['a', 'b', 'c'])'a b c'
    str.find() 查找子串首次出现的索引,找不到则返回 -1。 "hello".find('e')1
    str.index() 查找子串首次出现的索引,找不到抛出异常。 "hello".index('e')1
    str.count() 统计子串在字符串中出现的次数。 "hello".count('l')2
    str.startswith() 判断字符串是否以指定前缀开头。 "hello".startswith('he')True
    str.endswith() 判断字符串是否以指定后缀结尾。 "hello".endswith('lo')True
    str.isalpha() 判断字符串是否只包含字母。 "hello".isalpha()True
    str.isdigit() 判断字符串是否只包含数字。 "123".isdigit()True
    str.isalnum() 判断字符串是否只包含字母和数字。 "abc123".isalnum()True
    str.isspace() 判断字符串是否只包含空白字符。 " ".isspace()True
    str.swapcase() 大小写互换。 "HeLLo".swapcase()'hEllO'
    str.zfill(width) 在左侧填充 0 直到指定宽度。 "42".zfill(5)'00042'

    第二部分

    函数名 说明 使用示范
    str.partition() 将字符串按指定分隔符分为三部分(前、分隔符、后)。 "apple-banana".partition('-')('apple', '-', 'banana')
    str.rpartition() 从右侧开始按指定分隔符分割为三部分。 "apple-banana".rpartition('-')('apple', '-', 'banana')
    str.splitlines() 按行分割字符串,返回一个列表。 "a\nb\nc".splitlines()['a', 'b', 'c']
    str.expandtabs() 将字符串中的 \t 转换为指定数量的空格。 "a\tb".expandtabs(4)'a b'
    str.center(width, fillchar=' ') 在字符串两侧填充字符,使其居中。 "hello".center(11, '*')'***hello***'
    str.ljust(width, fillchar=' ') 在右侧填充字符,使字符串左对齐。 "hello".ljust(10, '-')'hello-----'
    str.rjust(width, fillchar=' ') 在左侧填充字符,使字符串右对齐。 "hello".rjust(10, '-')'-----hello'
    str.translate(table) 根据映射表替换字符。 "abc".translate(str.maketrans('a', 'A'))'Abc'
    str.maketrans(x, y, z=None) 创建字符映射表,用于 translate() str.maketrans('aeiou', '12345')
    str.format() 格式化字符串。支持变量替换。 "{}, {}".format('Hello', 'World')'Hello, World'
    str.format_map() 使用字典格式化字符串。 'Hello, {name}'.format_map({'name': 'Alice'})'Hello, Alice'
    str.casefold() 类似于 lower(),但处理更多语言场景。 "HELLO".casefold()'hello'
    str.encode() 将字符串编码为字节对象。 "hello".encode('utf-8')b'hello'
    str.decode() 将字节对象解码为字符串(通常与 encode() 搭配使用)。 b'hello'.decode('utf-8')'hello'
    str.islower() 判断字符串是否全为小写。 "hello".islower()True
    str.isupper() 判断字符串是否全为大写。 "HELLO".isupper()True
    str.isnumeric() 判断字符串是否只包含数字字符。 "12345".isnumeric()True
    str.isdecimal() 判断字符串是否只包含十进制字符。 "123".isdecimal()True

    作者:咱家阿星

    物联沃分享整理
    物联沃-IOTWORD物联网 » Python 字符串操作基础应用

    发表回复