Extract a single integer from a string

后端 未结 21 2953
一个人的身影
一个人的身影 2020-11-21 23:33

I want to extract the digits from a string that contains numbers and letters like:

"In My Cart : 11 items"

I want to extract the nu

21条回答
  •  感动是毒
    2020-11-22 00:01

    This script creates a file at first , write numbers to a line and changes to a next line if gets a character other than number. At last, again it sorts out the numbers to a list.

    string1 = "hello my name 12 is after 198765436281094and14 and 124de"
    f= open("created_file.txt","w+")
    for a in string1:
        if a in ['1','2','3','4','5','6','7','8','9','0']:
            f.write(a)
        else:
            f.write("\n" +a+ "\n")
    f.close()
    
    
    #desired_numbers=[x for x in open("created_file.txt")]
    
    #print(desired_numbers)
    
    k=open("created_file.txt","r")
    desired_numbers=[]
    for x in k:
        l=x.rstrip()
        print(len(l))
        if len(l)==15:
            desired_numbers.append(l)
    
    
    #desired_numbers=[x for x in k if len(x)==16]
    print(desired_numbers)
    

提交回复
热议问题