1.字符串的格式化输出
name = input("姓名:") age = input("年龄:") # str = "我叫" + name + ",我今年" +age # print(str) # 1 format(推荐) text = "我叫{0},我今天{1}岁".format(name, age) #占位符 print(text) # 2. % text1 = "我叫%s,我今天%d" %("aaa", 10) print(text1) str1 = "union is good man"
2.字符串独有功能
# 字符串独有的功能 # - 大小写 # - 开头、结尾 # - 切割 # - 连接 # - 替换 # - 是否是数字 # - 除去空白
str1 = "union is good man" # 1. # upper() 大写 # lower() 小写 print(str1.upper()) print(str1.lower()) # 2 # isdecimal : 判断是不是整数 v1 = "123" res = v1.isdecimal() print(res) # 3 # startswith/endswith : 是否以xxx开头/xxx结尾 add = input("请输入地址:") if add.startswith("北京"): print("京户") else: print("非京户") # 4 # replace:替换 text = "中国" data = text.replace("中国", "新中国") print(data) text1 = input("请输入评论:") data1 = text1.replace("移动", "xxx") print(data1) # 5. split|rsplit(从右往左切) : 切割,可以把字符串按照某种格式进行切割,其输出结果类型为list str1 = "union is a good man" str2 = str1.split(" ") # str2被切成了列表 print(str2) test = input("请输入文件名:") data = test.rsplit(".", maxsplit=1) print(data[0]) print(data[1]) info = input("用户和密码:") data_list = info.split(",", maxsplit=1) if data_list[0] == "root" and data_list[1] == "123": print("登录成功") else: print("登录失败") # 6.join 连接(拼接) v1 = ["张三", "李四", "周五"] data_list = "_".join(v1) print(v1) # 动态注册用户到列表 user_list1 = ["张三", "李四"] data_str = ",".join(user_list1) text = "平台注册用户有{0}".format(user_list1) print(text) # 7. maketrans t46 = str.maketrans("ac", "65") str47 = "aron is a good man" str48 = str47.translate(t46) print(str48) # 8.解码|编码 # encode data2 = "union is a good man" str53 = data2 .encode("utf-8") print(str53) # 9.strip|lstrip|rstrip :去除空白(头部和尾部),lstrip取出左边空白,rstrip除去右边的空白 info = "中国联通 " data = info.strip() print(data) # 字符串的公共功能 # 1.长度 、2.索引[0] [-1]、3.切片[2:4] name = "union is a nice man" name_len = len(name) print(name_len) print(name[0]) # 索引 name = "union is nice man" index = 0 while index < len(name): item = name[index] print(item) index += 1 # 切片 name = "union is nice man" print(name[2:4]) # 前取后不取
练习题:
# 练习题 # 代码实现,提示用户输入文本,是以中国开头,输出中国人,否则外国人 info = input("请输入x:") if info.startswith("中国x"): print("中国人") else: print("外国人") # 写代码,用户文本,文本中上替换下 text = input("地址是:") data = text.replace("上", "下") print(data) # 提示用户输入文本, 计算文本中"国"出现的次数 text1 = input("信息:") count = 0 for i in text1: if i == "国": count += 1 print("国的出现次数为{0}".format(count)) # 用户输入文本,含有数字和字母 fdafafas123weqr,将里面的数字提取出来 text2 = input("输入:") result = "" data_list = [] for item in text2: if item.isdecimal(): result = result + item data_list.append(item) print(result) print(data_list) print("".join(data_list)) # 输入电脑路径,程序自动寻找整个路径下所有的mp4后缀的文件 path = input("路径:") file_list = os.listdir(path) for name in file_list: group = name.rsplit(".", maxsplit=1) print(group[-1]) # 判断某个字符串是否包含某个子序列 test = "中国北京上海神州" if "中国" in test: print("在里面") else: print("不在里面")
标签:name,text,list,print,字符串,input,data From: https://www.cnblogs.com/zmc60/p/17006266.html