黑马程序员技术交流社区

标题: python技术贴 [打印本页]

作者: hm_Python_Plh    时间: 2018-7-30 23:44
标题: python技术贴
定义函数findall,实现对字符串find方法的进一步封装,要求返回符合要求的所有位置的起始下标, 如字符串"helloworldhellopythonhelloc++hellojava",需要找出里面所有的"hello"的位置,最后将返回一个元组(0,10,21,29),即将h的下标全部返回出来,而find方法只能返回第一个。

a_str = "helloworldhellopythonhelloc++hellojava"
b_str = "hello"
a_list = []
num = 0
while True:
    if b_str in a_str:
        num = a_str.index(b_str,num, len(a_str))
        a_list.append(num)
        print(a_str)
        print(a_list)
        num += 5
    else:
        print("完成")
        break



输出结果
helloworldhellopythonhelloc++hellojava
[0]
helloworldhellopythonhelloc++hellojava
[0, 10]
helloworldhellopythonhelloc++hellojava
[0, 10, 21]
helloworldhellopythonhelloc++hellojava
[0, 10, 21, 29]

总结:刚入门的小白,希望大牛多多指导



60469ef05baca85d7a206c7ce440ed86.png (42.38 KB, 下载次数: 7)

60469ef05baca85d7a206c7ce440ed86.png





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2