python正则表达式re.match

2024-10-08 22:28:36 发布

您现在位置:Python中文网/ 问答频道 /正文

import re

list=["22.11","23","66.7f","123abcde","Case44","Happy","78","66.7","yes123","Book111"]

def removeInt(list):
    
for str in list:
            
    if re.match("\d+",str):
       
           result=re.search("\d+",str)
           print("Original sentence:", str)
           print("Found integer",result.group(0),"at the beginning of the string, starting index",result.start(),"and ending index at index",result.end(),".The rest of the string is:"**???????????**)
  

removeInt(list)

大家好,我目前正在做一个python正则表达式练习,以上是我目前的代码。 在输出的末尾,如果我想在从字符串中删除整数后显示字符串的其余部分。 我可以使用什么功能

以下是一个输出示例:

Original sentence: “90years” 
Found integer 90 at the beginning of this string, starting at index _ ending at index _. The rest of the string is: years.

Tags: oftherestringindexintegerresultsentence
2条回答

我想您可以使用.find()字符串方法

The find() method returns the index of first occurrence of the substring (if found). If not found, it returns -1.

find()方法的语法为:

str.find(sub, start, end)

其中:

  • sub-它是要在str字符串中搜索的子字符串
  • 开始和结束(可选)-范围str[start:end]在此范围内 搜索子字符串

您可能会发现使用组捕获数字及其前后的字符串部分更容易。注意:我假设您不想在第一组之后匹配其他数字:

import re

list=["22.11","23","66.7f","123abcde","Case44","Happy","78","66.7","yes123","Book111"]

def removeInt(list):
    for str in list:
        result = re.match("([^\d]*)(\d+)(.*)",str)
        if result is not None:
            print("Original sentence:", str)
            print("Found integer",
                  result.group(2),
                  "in the string, starting at index",
                  result.start(2),
                  "and ending at index",
                  result.end(2),
                  ". The rest of the string is:", result.group(1)+result.group(3))
  
removeInt(list)

输出:

Original sentence: 22.11
Found integer 22 in the string, starting at index 0 and ending at index 2 . The rest of the string is: .11
Original sentence: 23
Found integer 23 in the string, starting at index 0 and ending at index 2 . The rest of the string is: 
Original sentence: 66.7f
Found integer 66 in the string, starting at index 0 and ending at index 2 . The rest of the string is: .7f
Original sentence: 123abcde
Found integer 123 in the string, starting at index 0 and ending at index 3 . The rest of the string is: abcde
Original sentence: Case44
Found integer 44 in the string, starting at index 4 and ending at index 6 . The rest of the string is: Case
Original sentence: 78
Found integer 78 in the string, starting at index 0 and ending at index 2 . The rest of the string is: 
Original sentence: 66.7
Found integer 66 in the string, starting at index 0 and ending at index 2 . The rest of the string is: .7
Original sentence: yes123
Found integer 123 in the string, starting at index 3 and ending at index 6 . The rest of the string is: yes
Original sentence: Book111
Found integer 111 in the string, starting at index 4 and ending at index 7 . The rest of the string is: Book

相关问题 更多 >

    热门问题