python 字符串 指定字符数量 python字符串所有字符个数_字符串

python字符串基本操作(详解)



目录

  • python字符串基本操作(详解)
  • 1. 创建字符串
  • 2. 连接字符串
  • 3. 字符串长度
  • 4. 字符串切片
  • 4.1 基本语法
  • 4.1.1 基本切片
  • 4.1.2. 省略开始或结束
  • 4.1.3. 使用步长
  • 4.1.4. 逆序字符串
  • 4.2 注意事项
  • 5. 字符串方法
  • 5.1. capitalize()
  • 5.2. upper()
  • 5.3. lower()
  • 5.4. title()
  • 5.5. strip()
  • 5.6. lstrip() 和 rstrip()
  • 5.7. find()
  • 5.8. replace(old, new)
  • 5.9. split(delimiter)
  • 5.10. join()
  • 5.11. startswith() 和 endswith()
  • 5.12. isalpha(), isdigit(), isalnum():
  • 5.13. count(substring)
  • 5.14. center(width, char)
  • 5.15. ljust()和 rjust()
  • 5.16. index
  • 5.17. insert
  • 6. 转义字符
  • 6.1. `\\` - 反斜杠
  • 6.2. `\'` - 单引号
  • 6.3. `\"` - 双引号
  • 6.4. `\n` - 换行符
  • 6.5. `\t` - 制表符(Tab)
  • 6.6. `\r` - 回车符(Carriage Return)
  • 6.7. \b - 退格符(Backspace)
  • 6.8. \f - 换页符
  • 6.9. \ooo - 八进制数表示的字符
  • 6.10. \xhh - 十六进制数表示的字符
  • 6.11. \uXXXX - Unicode字符
  • 7. 格式化字符串
  • 8. 检查字符串内容




Python 是一门强大的编程语言,其中字符串操作是其核心功能之一。在 Python 中,字符串是一个不可变的序列数据类型,以下是 Python 中常见的字符串操作:

1. 创建字符串

  • 使用单引号或双引号来定义一个字符串。
s1 = 'Hello'
s2 = "World"

2. 连接字符串

  • 使用 + 运算符将两个字符串连接在一起。
s3 = s1 + s2  # 输出: 'HelloWorld'

3. 字符串长度

  • 使用 len() 函数获取字符串的长度。
length = len(s1)  # 输出: 5

4. 字符串切片

4.1 基本语法

字符串切片的基本语法是:[开始:结束:步长]。其中,开始 是切片开始的位置,结束 是切片结束的位置(不包括此位置),步长 是切片中每两个字符之间的距离。

例如,考虑以下字符串:

s = "Python"

4.1.1 基本切片

  • 获取字符串的前三个字符。
print(s[0:3])   # 输出: "Pyt"
  • 获取字符串的最后三个字符。
print(s[-3:])   # 输出: "hon"

4.1.2. 省略开始或结束

  • 省略开始位置,默认为0。
print(s[:3])   # 输出: "Pyt"
  • 省略结束位置,默认为字符串的长度。
print(s[3:])   # 输出: "hon"

4.1.3. 使用步长

  • 使用步长为2的切片获取字符串中的每个第二个字符。
print(s[::2])   # 输出: "Pto"

4.1.4. 逆序字符串

  • 使用步长为-1的切片可以轻松地逆序一个字符串。
print(s[::-1])   # 输出: "nohtyP"

4.2 注意事项

  • 索引:Python 的索引是从 0 开始的。所以,s[0] 是字符串的第一个字符,s[1] 是第二个字符,依此类推。负索引则从字符串的末尾开始,s[-1] 是字符串的最后一个字符,s[-2] 是倒数第二个字符,等等。
  • 不可变性:由于字符串在 Python 中是不可变的,所以切片操作不会修改原始字符串,而是返回一个新的字符串。
  • 越界索引:切片操作是非常宽容的。即使你的开始或结束索引超出了字符串的范围,Python 也不会报错。例如,s[1:100] 在上述字符串中仍然有效,返回 “ython”。

5. 字符串方法

5.1. capitalize()

将字符串的首字母大写。

s = "python"
print(s.capitalize())  # 输出: "Python"

5.2. upper()

将所有字母转为大写。

s = "python"
print(s.upper())  # 输出: "PYTHON"

5.3. lower()

将所有字母转为小写。

s = "PYTHON"
print(s.lower())  # 输出: "python"

5.4. title()

将每个单词的首字母大写。

s = "hello world"
print(s.title())  # 输出: "Hello World"

5.5. strip()

删除字符串前后的空格(也可删除指定字符)。

s = "  python  "
print(s.strip())  # 输出: "python"

5.6. lstrip() 和 rstrip()

删除字符串左侧或右侧的空格。

s = "  python  "
print(s.lstrip())  # 输出: "python  "
print(s.rstrip())  # 输出: "  python"

5.7. find()

返回子字符串首次出现的位置,如果没有找到则返回-1。

s = "hello world"
print(s.find("world"))  # 输出: 6

5.8. replace(old, new)

替换字符串中的子字符串。

s = "hello world"
print(s.replace("world", "Python"))  # 输出: "hello Python"

5.9. split(delimiter)

根据分隔符分割字符串。

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

5.10. join()

使用指定的分隔符连接字符串序列。

fruits = ["apple", "banana", "orange"]
print(" & ".join(fruits))  # 输出: "apple & banana & orange"

5.11. startswith() 和 endswith()

检查字符串是否以指定的子字符串开始或结束。

s = "python.exe"
print(s.endswith(".exe"))  # 输出: True

5.12. isalpha(), isdigit(), isalnum():

检查字符串是否全部由字母、数字或字母和数字组成。

s1 = "python"
 s2 = "12345"
 s3 = "python12345"
 print(s1.isalpha())  # 输出: True
 print(s2.isdigit())  # 输出: True
 print(s3.isalnum())  # 输出: True

5.13. count(substring)

计算子字符串在字符串中出现的次数。

s = "banana"
print(s.count("a"))  # 输出: 3

5.14. center(width, char)

返回一个指定宽度的字符串,原字符串居中,使用指定字符填充。

s = "python"
print(s.center(20, '*'))  # 输出: "*******python*******"

5.15. ljust()和 rjust()

返回左对齐或右对齐的字符串,并使用指定字符填充。

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

5.16. index

index() 是 Python 列表的一个方法,用于返回列表中指定元素的第一个匹配项的索引。

lst = [1, 2, 3, 4, 3, 5]

# 获取元素3的索引
index_3 = lst.index(3)
print(index_3)  # 输出: 2

# 从索引3开始搜索元素3
index_3_from_3 = lst.index(3, 3)
print(index_3_from_3)  # 输出: 4

5.17. insert

insert() 是 Python 列表的一个方法,用于在指定的位置插入一个元素。

lst = [1, 2, 4, 5]

# 在索引2的位置插入元素3
lst.insert(2, 3)
print(lst)  # 输出: [1, 2, 3, 4, 5]

# 在列表的开头插入元素0
lst.insert(0, 0)
print(lst)  # 输出: [0, 1, 2, 3, 4, 5]

# 在列表的末尾插入元素6
lst.insert(len(lst), 6)
print(lst)  # 输出: [0, 1, 2, 3, 4, 5, 6]

6. 转义字符

6.1. \\ - 反斜杠

print("This is a backslash: \\")  # 输出: This is a backslash: \

6.2. \' - 单引号

print('It\'s a nice day!')  # 输出: It's a nice day!

6.3. \" - 双引号

print("She said, \"Hello!\"")  # 输出: She said, "Hello!"

6.4. \n - 换行符

print("First Line\nSecond Line")  # 输出:
# First Line
# Second Line

6.5. \t - 制表符(Tab)

print("Column1\tColumn2")  # 输出: Column1    Column2

6.6. \r - 回车符(Carriage Return)

它通常用于覆盖同一行的内容。

print("This will be overwritten\rThis is new")  # 输出: This is new

6.7. \b - 退格符(Backspace)

用于删除前一个字符。

print("Helloo\b")  # 输出: Hello

6.8. \f - 换页符

它用于打印机上,让打印内容开始于下一个新页。

print("This is on one page\fThis is on another page")

6.9. \ooo - 八进制数表示的字符

其中 ooo 是一个三位八进制数。

print("\141")  # 输出: a (因为141的八进制等于97的十进制,97是ASCII码中的'a')

6.10. \xhh - 十六进制数表示的字符

其中 hh 是一个两位十六进制数。

print("\x61")  # 输出: a (因为61的十六进制等于97的十进制,97是ASCII码中的'a')

6.11. \uXXXX - Unicode字符

其中 XXXX 是一个四位十六进制数。

print("\u03A9")  # 输出: Ω (希腊字母大写的欧米茄)

7. 格式化字符串

使用 .format() 方法或 f-string (Python 3.6+) 来格式化字符串。

name ="Alice"
 age = 30
 print("{} is {} years old.".format(name, age))  # 输出: 'Alice is 30 years old.'
 print(f"{name} is {age} years old.")            # 输出: 'Alice is 30 years old.'

8. 检查字符串内容

  • 使用 startswith(substring)endswith(substring) 来检查字符串是否以特定的子字符串开始或结束。
  • 使用 in 关键字来检查子字符串是否存在于字符串中。
s = "Python"
print(s.startswith("Py"))  # 输出: True
print("th" in s)           # 输出: True