
作者:CPP手艺人 来源: CPP手艺人 日期:2026-12-01 19:00:19
Python中(zhong)的字符串(str)是用于表示文本数据的一种基本数据类型,字符串可以(yi)包含字母、数字、符号和空格等字符,在Python中,字符串是不(bu)可(ke)变的,这意味着一旦创建(jian)了一个字符串,就不能更改它的内容。(图(tu)片来源网络,侵删)
1、创建字符串

在Python中,有多种方法(fa)可以创建字符串:

使用单引号或双引号:可(ke)以使用单引号(’)或双引号(")来创建字符串。

s1 = 'hello, world!'s2 = "hello, world!"
使(shi)用三引号:可(ke)以使用三个连续的单引号或双引号来创建多行字符串。
s3 = '''hello,world!'''s4 = """hello,world!"""
使用str()函数:可以使用str()函数将其他数据类(lei)型转换为字符串。
num = 123s5 = str(num) # 结果为 "123"
2、字符串操作
len():返回字符串的长度。
s = "hello, world!"print(len(s)) # 输出:13
lower():将字符串中的所有大写字母转换为小写字母。
s = "Hello, World!"print(s.lower()) # 输出:"hello, world!"
upper():将字符串中的所(suo)有小写字母转换为大写字母。
s = "Hello, World!"print(s.upper()) # 输出:"HELLO, WORLD!"split():根据指定(ding)的分隔符将字符串分割为一个列表。
s = "apple,banana,orange"print(s.split(",")) # 输出:['apple', 'banana', 'orange']join():使用指定的字符串将列(lie)表(biao)中的元素连(lian)接成一个新字符串。
words = ["apple", "banana", "orange"]s = ",".join(words)print(s) # 输出:"apple,banana,orange"
replace():将字符串中(zhong)的某个子串替换为另一个子串。
s = "I like cats."print(s.replace("cats", "dogs")) # 输出:"I like dogs."find():查找子串在字符串中(zhong)首次出现的位置,如果找不到,则返回1。
s = "hello, world!"print(s.find("world")) # 输出:7startswith():检查字符串是否以指定的子串开头(tou)。
s = "hello, world!"print(s.startswith("hello")) # 输出:Trueendswith():检查字符串是否以(yi)指定的子串结尾。
s = "hello, world!"print(s.endswith("!")) # 输出:Truestrip():去除字符串首尾的空白字符(包括空格、换行符和制表符)。
s = " hello, world! "print(s.strip()) # 输出:"hello, world!"
3、格式化字符串
Python提供了多(duo)种方法来格式化字符串,以便在字符串中插入变量值,以下是一些常用的字符串格式化方法:
使用%操作符:可以使用%操作符将变量插入到字符串中。
name = "Alice"age = 30print("My name is %s and I am %d years old." % (name, age)) # 输出:"My name is Alice and I am 30 years old."使用str.format()方(fang)法:可以使用str.format()方法将变量插入到字符串中。
name = "Alice"age = 30print("My name is { } and I am { } years old.".format(name, age)) # 输出(chu):"My name is Alice and I am 30 years old."使用fstring(Python 3.6+):可以(yi)使用(yong)fstring在字符串前加(jia)上f或F,然后在字符串中(zhong)使用花(hua)括号{ }包裹变量名。
name = "Alice"age = 30print(f"My name is { name} and I am { age} years old.") # 输出:"My name is Alice and I am 30 years old."以上就(jiu)是关于Python字符串的基本用法和操作的介绍,希望对(dui)你有所帮助!