Python Day 字符串函数、循环、ifelse 条件和任务
查找():
在字符串中搜索指定值并返回找到它的位置。
例如:
txt = "hello, welcome to my world." x = txt.find("welcome") print(x)
输出:
7
因此 welcome 根据索引位于第七位。如果给出任何其他未定义的单词,则结果将为 -1。
注意:在上面的例子中,如果使用索引函数而不是find,那么它将显示“valueerror:子字符串未找到”。如果定义,则输出将与find函数相同。
循环:
for循环:
例如:1
txt = '1234' for num in txt: print(num,end=' ')
输出:
1 2 3 4
例如:2
name = input("enter name: ") print(name) for alphabet in name: print(alphabet, end='*')
输出:
enter name: guru guru g*u*r*u*
如果:
它根据语句的真假来决定运行程序。
例如:
txt = '12a4' for num in txt: if num>='0' and num<='9': print(num,end=' ') else: print('not decimal',end=' ')
输出:
1 2 not decimal 4
在上面的示例中,1,2,4 是十进制,但 a 不是小数,因此在输出中,根据其他条件,它显示的不是十进制。
任务:
拉克希米·普里塔
大师 prasanna
古汉拉贾
瓦拉塔拉扬
查找:
1: 以字母“g”开头的名字
2:名称以“a”结尾
3:名称之间有空格
4:名字超过9个字母
name=input("enter names: ") names=(name).split(",") for letter in names: if letter.startswith('g'): print("names starts with g are: ",letter) else : letter.endswith('a') print("names end with a are: ",letter) for space in names: for word in space: if word==' ': print("names with space: ",space) else: continue for character in names: if len(character)>9: print("names with more than 9 letters: ",character)
输出:
Enter names: guru prasanna,guhanraja,lakshmi pritha,varatharajan Names starts with g are: guru prasanna Names starts with g are: guhanraja Names end with a are: lakshmi pritha Names end with a are: varatharajan Names with space: guru prasanna Names with space: lakshmi pritha Names with more than 9 letters: guru prasanna Names with more than 9 letters: lakshmi pritha Names with more than 9 letters: varatharajan