Python 字符串

173 阅读6分钟

修订历史:

1 什么是字符串

引号:引号的作用是定义字符串。,包括四种类型

  • 单引号 ('):用于定义单行字符串,可以在字符串内部使用双引号而不需要转义。
  • 双引号 ("):用于定义单行字符串,可以在字符串内部使用单引号而不需要转义。
  • 单三引号 ('''):用于定义多行字符串,可以在字符串内部自由使用单引号和双引号。
  • 双三引号 ("""):用于定义多行字符串,可以在字符串内部自由使用单引号和双引号
# 单引号用于创建一个字符串
>>> single_quote_str = 'This is a string with single quotes.'
>>> print(single_quote_str)
This is a string with single quotes.

# 双引号与单引号的功能相同,也用于创建字符串
>>> double_quote_str = "This is a string with double quotes."
>>> print(double_quote_str)
This is a string with double quotes.

# 三引号(单三引号或双三引号)用于创建多行字符串,或者在字符串中包含单引号、双引号而不需要转义。
>>> triple_single_quote_str = '''This is a multi-line string
... with single quotes that can contain "double quotes" without escaping.'''
>>> print(triple_single_quote_str)
This is a multi-line string
with single quotes that can contain "double quotes" without escaping.

>>> triple_double_quote_str = """This is a multi-line string
... with double quotes that can contain 'single quotes' without escaping."""
>>> print(triple_double_quote_str)
This is a multi-line string
with double quotes that can contain 'single quotes' without escaping.

2 字符串常量

>>> import string
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

字符串在Python中是不可变的,即一旦创建,其内容不能更改。

# 初始化字符串 s 为 "Data"
>>> s = 'Hello'

# t 是 s 的一个引用(别名)
>>> t = s

# 修改 s 的值
>>> s += 'World'

# 打印 s 和 t 的 id,以确认它们是否指向同一个对象
>>> print(id(s))  # 打印 s 的 id
>>> print(id(t))  # 打印 t 的 id

# 打印 s 和 t 的值
>>> print(s)      # 打印 s 的值
>>> print(t)      # 打印 t 的值
139633013769200
139633013561904
HelloWorld
Hello

当我们进行字符串拼接操作时,实际上是创建了一个新的字符串对象。如上述演示代码所示,变量名 s 和 t 是对字符串对象的引用。虽然最初它们指向同一个对象,但通过赋值操作 s += 'World's 被重新赋值为一个新的字符串对象,而 t 仍然指向原始的字符串对象。

3 字符串运算

  • 字符串连接:使用 + 运算符连接两个字符串。
  • 字符串重复:使用 * 运算符重复一个字符串。
  • 字符串切片:使用方括号 [] 访问字符串中的字符。
  • 字符串索引:使用方括号 [] 访问字符串中的字符。
# 字符串加法
>>> "Hello" + " World"
'Hello World'

# 字符串乘法
>>> "Hello " * 3
'Hello Hello Hello '

# 字符串切片和索引
>>> s = "Hello World"
>>> print(s[::-1])
>>> def reverse_string(s):
...     return s[::-1]
... 
>>> reverse_string("Hello World")
'dlroW olleH'

# 不支持字符串和整数相加
>>> "Hello" + 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly

# 不支持字符串与字符串相乘
>>> "hello" * 'e'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'str'

# 不支持字符串与浮点型相乘
>>> "Hello" * 3.5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't multiply sequence by non-int of type 'float'

4 常用字符串函数和方法

字符串相关函数

  • len():返回字符串的长度。
  • str():将任何对象转换为字符串。
  • ord():返回字符的 ASCII 码。
  • chr():返回 ASCII 码对应的字符。

字符串方法

  • lower():将字符串中的所有字符转换为小写。
  • upper():将字符串中的所有字符转换为大写。
  • capitalize():将字符串的第一个字符转换为大写,其余字符转换为小写。
  • title(): 将字符串中的每个单词的第一个字符转换为大写,其余字符转换为小写。
  • swapcase():将字符串中的所有字母转换为相反的大小写。
  • strip():删除字符串中的前导和尾随空白字符。
  • lstrip():删除字符串中的前导空白字符。
  • rstrip():删除字符串中的尾随空白字符。
  • replace():替换字符串中的所有匹配项。
  • split():将字符串拆分为一个列表,根据一个分隔符(默认为空格)拆分字符串。

5 编程题

5.1 字符方法 string.find()

题目描述:输入一串字符串S和一个单词W,要求编写程序,判断单词W是否存在于字符串S当中,并输出响应内容。

# 输入一串字符串`S`和一个单词`W`,要求编写程序,判断单词`W`是否存在于字符串`S`当中,并输出响应内容。
s, w = input().split(",")

# 查找子串的位置
start_index = s.find(w)

# 判断是否找到子串
if start_index != -1:
    print(f"The starting point of {s} is {start_index+1}")
else:
    print("not found")

输入 crazyThurvme50,me, 输出为 The starting point of crazyThurvme50 is 11

5.2 字符串切片和索引

题目描述:输入三串字符串(逗号隔开)str1,str2,str3,要求编写程序,判断这些字符串是否为回文字符串,如果是则输出T,否则输出F

def is_palindrom_string(s):
    """
    判断一个字符串是否为回文字符串
    """
    if not isinstance(s, str):
        raise ValueError("Input must be a string")
    if s == s[::-1]:
        return "T"
    else:
        return "F"


str1, str2, str3 = input().split(",")
print("%s,%s,%s" %(is_palindrom_string(str1), is_palindrom_string(str2), is_palindrom_string(str3)))

输入:abc,bbb,abcdcba, 输出 F,T,T

5.3 字符串运算与string.join()方法

题目描述: 输入三串字符串(逗号隔开)str1,str2,str3,要求编写程序,提取每串字符串最末端一个字符,合并组成一个新的字符串并输出。

str1, str2, str3 = input().split(",")
# print(str1[-1] + str2[-1] + str3[-1])

last_chars = []
for s in [str1, str2, str3]:
    if s:
        last_chars.append(s[-1])
    else:
        last_chars.append("")

print("".join(last_chars))

输入为APP,222,CS, 输出 P2S

题目描述: 输入一串句子(不含标点符号),单词与单词之间以空格隔开,要求编写程序,将单词顺序进行翻转,但不翻转每个单词的内容。

str1 = input()

if not str1:
    print("Input cannot be empty.")
else:
    # 分割字符串并反转单词顺序
    words = str1.split()
    reversed_words = " ".join(words[::-1])
    print(reversed_words)

输入为This works but is confusing, 输出为 confusing is but works This

5.4 字符串 string.swapcase() 方法

题目描述:输入一串字符串str1,要求编写程序,将其中所有的大写字母和小写字母进行转换,输出转换后字符串。

str1 = input()

# 验证输入是否为空
if not str1:
    print("Input is empty")
    exit(1)

print(str1.swapcase())

输入为abcdEFG, 输出为ABCDefg