python_基础_18


字符串的基本使用

字符串的操作

  • 在python交互界面定义一个字符串,例如:hello_str = ""
  • 输入hello_str.按下TAB键,交互界面就会提供字符串的所有操作方法
字符串操作演练-1
# 判断空白字符
# \t是对齐符,\n是换行符,\r是回车符,这些都是空白字符
space_str = "   \t\n\r"
print(space_str.isspace())

# 判断字符串中只包含数字
num_str = "1"
# 都不能判断小数
print(num_str.isdecimal())  # 只判断阿拉伯数字
print(num_str.isdigit())    # 除阿拉伯数字外还可判断特殊字符,比如unicode字符串"\u00b2"
print(num_str.isnumeric())  # 除 isdigit 的功能外,还可以判断中文数字

# 字符串的查找和替换
hello_str = "hello world"
# 判断是否以指定字符串开始
print(hello_str.startswith("hello"))
# 判断是否以指定字符串结尾
print(hello_str.endswith("world"))
# 查找指定字符串
print(hello_str.find("llo"))
# index同样可以查找指定的字符串在大字符串中的索引,但是字符串不存在,find方法会返回-1
print(hello_str.find("abc"))

# 替换字符串
hello_str.replace("world","python")
# replace方法执行完成后,会返回一个新的字符串,但是不会修改原有的字符串内容
print(hello_str)
字符串操作演练-2
# 要求:顺序并且居中对齐输出以下内容
poem = ["登鹳雀楼",
        "王之涣",
        "白日依山尽",
        "黄河入海楼",
        "欲穷千里目",
        "更上一层楼"]
 for poem_str in poem:
     print("|%s|" % poem_str.center(10," "))  # ||是参考线

# 向左对齐
# for poem_str in poem:
    # print("|%s|" % poem_str.ljust(10," "))

# 向右对齐
# for poem_str in poem:
    # print("|%s|" % poem_str.rjust(10," "))
字符串操作演练-3
poem = ["\t\n登鹳雀楼",
        "王之涣",
        "白日依山尽\t\n",
        "黄河入海楼",
        "欲穷千里目",
        "更上一层楼"]

for poem_str in poem:
     # 先使用strip方法去除字符串中的空白字符
     # 再使用center方法居中显示文本
     print("|%s|" % poem_str.strip().center(10," "))
字符串操作演练-4
# 字符串的拆分和合并
poem_str = "登鹳雀楼\t 王之涣 \t 白日依山尽 \t \n 黄河入海楼 \t\t 欲穷千里目 \n 更上一层楼"
print(poem_str)

# 拆分字符串
poem_list = poem_str.split()
print(poem_list)

# 合并字符串
result = " ".join(poem_list)  # 使用" "作为分隔符
print(result)

文章作者: 张忠楠
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 张忠楠 !
评论
 上一篇
python_基础_19 python_基础_19
完整的for循环 for num in (1,2,3): print(num) if num == 2: break else: # 如果循环体内部使用break退出循环 # else
2020-04-17
下一篇 
python_基础_17 python_基础_17
字典的基本使用 字典和列表的区别 列表是有序的数据集合 字典是无序的数据集合 字典使用大括号{}定义 字典使用键值对存储数据,键值对之间使用,分隔 键key是索引 值value是数据 键和值之间用:分隔 键必
2020-04-17
  目录