温馨提示×

python中str怎么使用

小亿
131
2023-08-28 11:51:45
栏目: 编程语言

Python中str是一种字符串类型的数据结构,用于表示文本信息。可以通过以下方式使用str:

  1. 创建一个字符串对象:
s = "Hello, World!"
  1. 访问字符串中的字符:
print(s[0])  # 输出:H
  1. 获取字符串的长度:
print(len(s))  # 输出:13
  1. 字符串切片:
print(s[7:12])  # 输出:World
  1. 字符串拼接:
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2
print(s3)  # 输出:Hello, World
  1. 字符串格式化:
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age))  # 输出:My name is Alice and I'm 25 years old.
  1. 字符串查找和替换:
s = "Hello, World!"
print(s.find("World"))  # 输出:7
print(s.replace("Hello", "Hi"))  # 输出:Hi, World!
  1. 字符串大小写转换:
s = "Hello"
print(s.lower())  # 输出:hello
print(s.upper())  # 输出:HELLO
  1. 字符串分割和连接:
s = "Hello, World!"
print(s.split(","))  # 输出:['Hello', ' World!']
print(" ".join(['Hello', 'World!']))  # 输出:Hello World!
  1. 判断字符串是否以指定的前缀或后缀开始/结束:
s = "Hello, World!"
print(s.startswith("Hello"))  # 输出:True
print(s.endswith("World!"))  # 输出:True

这些是常见的字符串操作方法,可以根据需要来使用。

0