Python 字符串,字符串操作

demo.py(字符串的定义、遍历):

str1 = "hello python"  # 用单引号或双引号定义
str2 = '我的外号是"大西瓜"'

print(str2)
print(str1[6])

# 遍历字符串
for char in str2:
    print(char)

demo.py(字符串的长度len、子串出现次数count、子串出现位置index):

hello_str = "hello hello"

# 1. 统计字符串长度
print(len(hello_str))

# 2. 统计某一个小(子)字符串出现的次数
print(hello_str.count("llo"))  # 2
print(hello_str.count("abc"))  # 0

# 3. 某一个子字符串出现的位置
print(hello_str.index("llo"))
# 注意:如果使用index方法传递的子字符串不存在,程序会报错!
print(hello_str.index("abc"))  # 不存在,会报错

demo.py(isspace是否为空白字符串、isdecimal是否是数字字符串):

# 1. 判断空白字符
space_str = "      \t\n\r"

print(space_str.isspace())  # ""返回False

# 2. 判断字符串中是否只包含数字
# 1> 都不能判断小数
# num_str = "1.1"
# 2> unicode 字符串
# num_str = "\u00b2"
# 3> 中文数字
num_str = "一千零一"

print(num_str)
print(num_str.isdecimal())  # "1"  常用
print(num_str.isdigit())    # "1"  "①"  "\u00b2"(平方符号)
print(num_str.isnumeric())  # "1"  "①"  "\u00b2"  "一千零一"

demo.py(字符串startswith、endswith、find查找、replace替换):

hello_str = "hello world"

# 1. 判断是否以指定字符串开始
print(hello_str.startswith("hello"))  # True  区分大小写

# 2. 判断是否以指定字符串结束
print(hello_str.endswith("world"))

# 3. 查找指定字符串
# index同样可以查找指定的字符串在大字符串中的索引
print(hello_str.find("llo"))  # 2
# index如果指定的字符串不存在,会报错
# find如果指定的字符串不存在,会返回-1
print(hello_str.find("abc"))  # -1

# 4. 替换字符串
# replace方法执行完成之后,会返回一个新的字符串
# 注意:不会修改原有字符串的内容
print(hello_str.replace("world", "python"))  # hello python   默认替换所有

print(hello_str)  # hello world   原字符串不变

demo.py(strip去除前后空白、center文本对齐):

# 假设:以下内容是从网络上抓取的
# 要求:顺序并且居中对齐输出以下内容
poem = ["\t\n登鹳雀楼",
         "王之涣",
         "白日依山尽\t\n",
         "黄河入海流",
         "欲穷千里目",
         "更上一层楼"]

for poem_str in poem:

    # 先使用strip方法去除字符串前后的空白字符
    # 再使用center方法居中显示文本
    print("|%s|" % poem_str.strip().center(10, " "))  # center 第一个参数:宽度; 第二个参数:填充字符

demo.py(split拆分、join拼接):

# 假设:以下内容是从网络上抓取的
# 要求:
# 1. 将字符串中的空白字符全部去掉
# 2. 再使用 " " 作为连接符,拼接成一个字符串
poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海流 \t\t 欲穷千里目 \t\t\n更上一层楼"

print(poem_str)

# 1. 拆分字符串
poem_list = poem_str.split()  # 默认以空白字符分割。 返回列表
print(poem_list)

# 2. 合并字符串
result = " ".join(poem_list)  # 以空白字符,拼接字符串
print(result)

demo.py(字符串截取(切片),[开始索引:结束索引:步长]):

# 字符串的截取  字符串[开始索引:结束索引:步长]
num_str = "0123456789"

print(num_str[2:6])  # 2345  包含起始索引,不包含结束索引。 步长默认是1
print(num_str[2:])   # 23456789  默认截取到末尾
print(num_str[2:-1])  # 2345678  -1表示最后的索引。 不包含结束索引。
print(num_str[-2:])  # 89     截取末尾两个字符

print(num_str[0:6])  # 012345
print(num_str[:6])   # 012345  默认从起始开始截取
print(num_str[:])    # 0123456789

print(num_str[::2])    # 02468  步长(每隔步长个字符截取一个字符)

print(num_str[-1::-1])  # 9876543210  逆序(反转)。 步长-1,从末尾开始截取。 (开始索引-1可以省略)

猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/83933353