python字符串的所有用法

python字符串的用法

python字符串的用法

Python 中的字符串是不可变的序列,用于表示文本数据。字符串可以用单引号 ‘、双引号 " 或三引号 ‘’’ 或 “”" 来定义。以下是一些常见的字符串用法和操作:

1. 创建字符串

s1 = 'Hello, World!'
s2 = "Python is fun"
s3 = '''This is a multi-line
string in Python.'''
s4 = """Another multi-line
string example."""

2. 字符串拼接

可以使用 + 运算符来拼接字符串:

s1 = "Hello"
s2 = "World"
s = s1 + ", " + s2 + "!"
print(s)  # 输出: Hello, World!

3. 字符串重复

使用 * 运算符可以重复字符串:

s = "Python " * 3
print(s)  # 输出: Python Python Python 

4. 字符串索引和切片

字符串中的每个字符都有一个索引,索引从 0 开始。可以使用索引访问单个字符,或使用切片访问子字符串:

s = "Python"
print(s[0])    # 输出: P
print(s[-1])   # 输出: n (负索引表示从末尾开始)
print(s[1:4])  # 输出: yth (切片从索引1到3)
print(s[:3])   # 输出: Pyt (从开头到索引2)
print(s[3:])   # 输出: hon (从索引3到末尾)

5. 字符串长度

使用 len() 函数获取字符串的长度:

s = "Python"
print(len(s))  # 输出: 6

6.字符串方法

Python 提供了许多内置的字符串方法,以下是一些常用的方法:

str.upper(): 将字符串转换为大写。
str.lower(): 将字符串转换为小写。
str.strip(): 去除字符串两端的空白字符。
str.replace(old, new): 替换字符串中的子字符串。
str.split(sep): 根据分隔符将字符串拆分为列表。
str.join(iterable): 将可迭代对象中的元素连接成一个字符串。
str.find(sub): 查找子字符串的索引,如果找不到返回 -1。
str.startswith(prefix): 检查字符串是否以指定前缀开头。
str.endswith(suffix): 检查字符串是否以指定后缀结尾。

s = "  Python Programming  "
print(s.upper())          # 输出:   PYTHON PROGRAMMING  
print(s.lower())          # 输出:   python programming  
print(s.strip())          # 输出: Python Programming
print(s.replace("P", "J")) # 输出:   Jython Jrogramming  
print(s.split(" "))       # 输出: ['', '', 'Python', 'Programming', '', '']
print("-".join(["Python", "Programming"]))  # 输出: Python-Programming
print(s.find("Prog"))     # 输出: 10
print(s.startswith("Py")) # 输出: False
print(s.endswith("ing  ")) # 输出: True

7. 字符串格式化

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

% 格式化(旧式):

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

str.format():

name = "Bob"
age = 30
s = "My name is {} and I am {} years old.".format(name, age)
print(s)  # 输出: My name is Bob and I am 30 years old.

f-string(Python 3.6+):

name = "Charlie"
age = 35
s = f"My name is {name} and I am {age} years old."
print(s)  # 输出: My name is Charlie and I am 35 years old.

8. 字符串转义字符

字符串中可以使用转义字符来表示特殊字符,常见的转义字符包括:

\n: 换行
\t: 制表符
: 反斜杠
': 单引号
": 双引号

s = "This is a line.\nThis is another line."
print(s)
# 输出:
# This is a line.
# This is another line.

9. 字符串不可变性

字符串是不可变的,意味着一旦创建,就不能修改其中的字符。如果需要修改字符串,可以创建一个新的字符串。

s = "Python"
# s[0] = 'J'  # 这行代码会报错,因为字符串不可变
s = 'J' + s[1:]
print(s)  # 输出: Jython

10. 字符串成员检查

可以使用 in 和 not in 运算符检查子字符串是否存在于字符串中:

s = "Python Programming"
print("Python" in s)  # 输出: True
print("Java" not in s)  # 输出: True

11. 原始字符串

在字符串前加上 r 或 R 可以创建原始字符串,原始字符串中的转义字符不会被处理:

s = r"C:\Users\Name\Documents"
print(s)  # 输出: C:\Users\Name\Documents

12. 字符串编码与解码

字符串可以编码为字节,字节也可以解码为字符串:

s = "Python"
b = s.encode('utf-8')  # 编码为字节
print(b)  # 输出: b'Python'
s2 = b.decode('utf-8')  # 解码为字符串
print(s2)  # 输出: Python

13. 字符串比较

字符串可以使用 ==、!=、<、> 等运算符进行比较,比较是基于字符的Unicode值:

s1 = "apple"
s2 = "banana"
print(s1 == s2)  # 输出: False
print(s1 < s2)   # 输出: True (因为 'a' < 'b')

14. 字符串格式化对齐

可以使用 str.ljust()、str.rjust() 和 str.center() 方法来对齐字符串:

s = "Python"
print(s.ljust(10, '-'))  # 输出: Python----
print(s.rjust(10, '-'))  # 输出: ----Python
print(s.center(10, '-')) # 输出: --Python--

15. 字符串检查方法

Python 提供了一些方法来检查字符串的内容:

str.isalpha(): 检查字符串是否只包含字母。
str.isdigit(): 检查字符串是否只包含数字。
str.isalnum(): 检查字符串是否只包含字母和数字。
str.isspace(): 检查字符串是否只包含空白字符。
str.islower(): 检查字符串是否全部为小写。
str.isupper(): 检查字符串是否全部为大写。

s1 = "Python"
s2 = "123"
s3 = "Python123"
print(s1.isalpha())  # 输出: True
print(s2.isdigit())  # 输出: True
print(s3.isalnum())  # 输出: True
posted @ 2026-09-21 22:51  程序员小码  阅读(7)  评论(0)    收藏  举报