1、输入一个姓名,判断是否姓王 2、strip和replace的用法

1、endswith() 方法用于判断字符串是否以指定后缀结尾,如果以指定后缀结尾返回True,否则返回False。可选参数"start"与"end"为检索字符串的开始与结束位置。endswith()方法语法:str.endswith(suffix[, start[, end]])

import re
str1 = input("请输入名字:")
if '王' in re.findall('^王',str1):
    print("这个人是")
else:
    print("不是姓王")

if str1.startswith("王"):
    print(True)
else:
    print(False)

  

2、replace的用法:replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。replace()方法语法:str.replace(old, new[, max]) 参数 old -- 将被替换的子字符串。 new -- 新字符串,用于替换old子字符串。 max -- 可选字符串, 替换不超过 max 次

a = " welcome to my world   "
b = a.replace(" ","-")
print(b)

strip  注释:strip() 方法用于移除字符串头尾指定的字符(默认为空格)或字符序列。strip()方法语法:str.strip([chars]); 参数 chars -- 移除字符串头尾指定的字符序列。 返回移除字符串头尾指定的字符序列生成的新字符串

a = " welcome to my world   "
b = a.strip()
print(a)
print(b)

原文地址:https://www.cnblogs.com/cafe910912/p/15045351.html