Python 3 字符串详解
                           
天天向上
发布: 2025-03-14 22:17:21

原创
456 人浏览过

Python 3 中的字符串是不可变的(即字符串内容不能修改),并且支持多种操作,如索引、切片、格式化、内置方法等。字符串在 Python 中属于 str 类型。


1. 字符串的定义

在 Python 3 中,字符串可以用单引号 '、双引号 " 或三引号 ''' """ 表示。

📌 示例代码:

str1 = 'Hello'
str2 = "Python"
str3 = '''This is
a multi-line
string'''
print(str1, str2, str3)

2. 访问字符串

Python 支持索引(Indexing)和切片(Slicing) 来访问字符串中的字符。

(1)索引

字符串中的字符可以通过索引(从 0 开始)访问,负数索引从 -1 开始。

📌 示例代码:

s = "Python"
print(s[0])   # P
print(s[-1])  # n
print(s[2])   # t

(2)切片

切片用于获取字符串的一部分,语法:string[start:end:step]

📌 示例代码:

s = "Hello, Python"
print(s[0:5])    # Hello
print(s[:5])     # Hello(默认从 0 开始)
print(s[7:])     # Python(默认到末尾)
print(s[::2])    # Hlo yhn(步长为2)
print(s[::-1])   # 反转字符串

3. 字符串拼接与重复

Python 允许使用 +(拼接)*(重复) 操作字符串。

📌 示例代码:

str1 = "Hello"
str2 = "Python"
print(str1 + " " + str2)  # Hello Python
print(str1 * 3)           # HelloHelloHello

4. 常用字符串方法

Python 提供了丰富的字符串方法,以下是常用的操作:

方法说明示例
len(s)获取字符串长度len("Python") → 6
s.lower()转小写"HELLO".lower() → "hello"
s.upper()转大写"hello".upper() → "HELLO"
s.strip()去除两端空格" Python ".strip() → "Python"
s.lstrip()去除左侧空格" Python".lstrip() → "Python"
s.rstrip()去除右侧空格"Python ".rstrip() → "Python"
s.replace(old, new)替换字符串"Hello".replace("H", "J") → "Jello"
s.split(delim)拆分字符串"a,b,c".split(",") → ['a', 'b', 'c']
s.join(iterable)连接字符串" ".join(['a', 'b', 'c']) → "a b c"
s.startswith(sub)是否以 sub 开头"Python".startswith("Py") → True
s.endswith(sub)是否以 sub 结尾"Python".endswith("on") → True
s.find(sub)查找 sub,返回索引"hello".find("l") → 2
s.count(sub)统计 sub 出现次数"banana".count("a") → 3

📌 示例代码:

s = "  Hello, Python!  "
print(s.strip())       # "Hello, Python!"
print(s.lower())       # "  hello, python!  "
print(s.replace("Hello", "Hi"))  # "  Hi, Python!  "
print(s.split(","))    # ['  Hello', ' Python!  ']
print("-".join(["Hello", "Python"]))  # "Hello-Python"

5. 字符串格式化

Python 提供了 三种字符串格式化 方式:

(1)% 格式化

类似于 C 语言风格:

name = "Alice"
age = 25
print("My name is %s and I am %d years old." % (name, age))
# My name is Alice and I am 25 years old.

(2)format() 方法

print("My name is {} and I am {} years old.".format(name, age))
# My name is Alice and I am 25 years old.

print("My name is {0} and I am {1} years old.".format(name, age))
# My name is Alice and I am 25 years old.

(3)f-strings(Python 3.6+ 推荐)

print(f"My name is {name} and I am {age} years old.")
# My name is Alice and I am 25 years old.

6. 判断字符串

Python 提供了一些方法来判断字符串的特性:

方法说明示例
s.isalpha()是否全是字母"abc".isalpha() → True
s.isdigit()是否全是数字"123".isdigit() → True
s.isalnum()是否全是字母或数字"abc123".isalnum() → True
s.isspace()是否全是空白字符" ".isspace() → True
s.istitle()是否是标题格式"Hello World".istitle() → True

📌 示例代码:

s = "Python3"
print(s.isalpha())   # False (包含数字)
print(s.isdigit())   # False (包含字母)
print("123".isdigit())  # True
print("Hello World".istitle())  # True

7. 转义字符

Python 使用 \(反斜杠) 进行转义:

转义字符说明
\n换行
\t制表符
\'单引号
\"双引号
\\反斜杠

📌 示例代码:

print("Hello\nPython")  # 换行
print("Hello\tPython")  # 制表符
print("I\'m learning Python")  # 转义单引号

8. 原始字符串(r”…”)

如果你不想让 \ 被转义,可以使用 原始字符串(在字符串前加 r)。

📌 示例代码:

print(r"C:\Users\Python")  # C:\Users\Python

总结

  • 字符串索引(从 0 开始)和 切片s[start:end:step]
  • 字符串不可变
  • 字符串拼接(+)和重复(*
  • 字符串方法strip()replace()split()join() 等)
  • 三种格式化字符串方式%format()f-strings
  • 判断字符串特性的方法isdigit()isalpha()isspace() 等)
  • 转义字符\n\t 等)和 原始字符串(r"..."

你可以尝试这些代码,在 Python 终端运行并体验字符串的强大功能!更多详细内容请关注其他相关文章!

发表回复 0

Your email address will not be published. Required fields are marked *