Python 字符串

Python 字符串

Python 中的字符串是一种常见且重要的数据类型,用于存储文本信息。字符串是不可变的,即一旦创建,就不能更改其内容。但我们可以创建新的字符串作为修改的结果。以下是关于 Python 字符串的一些基本操作和功能的介绍。

数据类型转字符串

在 Python 中,你可以使用 str() 函数将其他数据类型转换为字符串。这对于在字符串中包含数字、浮点数、布尔值或其他数据类型时非常有用。

num = 123
float_num = 123.45
bool_value = True

str_num = str(num)
str_float = str(float_num)
str_bool = str(bool_value)

print(str_num)      # 输出: '123'
print(str_float)    # 输出: '123.45'
print(str_bool)     # 输出: 'True'

在字符串中使用变量

Python 支持在字符串中嵌入变量,这通常通过使用格式化字符串来实现。在 Python 3.6 及更高版本中,可以使用 f-string(格式化字符串字面值)。

name = "Alice"
age = 30

# 使用 f-string  
print(f"Hello, {name}. You are {age} years old.")
# 输出: Hello, Alice. You are 30 years old.

字符转义序列

在字符串中,某些字符具有特殊含义,如换行符\n、制表符\t等。要在字符串中包含这些字符而不触发其特殊含义,可以使用转义字符 \。

escaped_string = "This is a string with a newline character\nand another line."
print(escaped_string)
# 输出将包含两行文本
"""
This is a string with a newline character
and another line.
"""

其他转义序列

转义序列 含义
\n 换行符
\t 水平制表符(Tab)
\r 回车符
\\ 反斜杠(\)本身
\' 单引号(')
\" 双引号(")
\ooo 八进制数表示的字符(ooo是八进制数)
\xhh 十六进制数表示的字符(hh是十六进制数)
\uxxxx\Uxxxxxxxx Unicode字符(xxxx或xxxxxxxx是十六进制数)

分割字符串

split() 方法用于将字符串分割成子字符串列表。默认情况下,它使用空格作为分隔符,但你可以指定其他分隔符。

s = "apple,banana,orange"
fruits = s.split(',')
print(fruits)  # 输出: ['apple', 'banana', 'orange']

替换字符串

replace() 方法用于在字符串中查找并替换子字符串。

s = "Hello, world!"
new_s = s.replace("world", "Python")
print(new_s)  # 输出: Hello, Python!

修改字符串的大小写

Python 提供了几个方法用于修改字符串的大小写:

  • upper():将字符串中的所有字符转换为大写。
  • lower():将字符串中的所有字符转换为小写。
  • capitalize():将字符串的首字母转换为大写,其余部分转换为小写。
  • title():将字符串中每个单词的首字母转换为大写。
s = "hello world"
print(s.upper())      # 输出: HELLO WORLD
print(s.lower())      # 输出: hello world
print(s.capitalize()) # 输出: Hello world
print(s.title())      # 输出: Hello World

删除空白

Python 提供了几种方法用于删除字符串中的空白(包括空格、制表符、换行符等):

  • strip():删除字符串开头和结尾的空白。
  • lstrip():删除字符串开头的空白。
  • rstrip():删除字符串结尾的空白。
s = "   Hello, world!   "
print(s.strip())  # 输出: Hello, world!
print(s.lstrip()) # 输出: Hello, world!   
print(s.rstrip()) # 输出:   Hello, world!
posted @ 2024-06-11 16:34  测试小罡  阅读(884)  评论(0编辑  收藏  举报