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.
答案 0 :(得分:2)
您可能会发现使用组更容易捕获数字以及它们前后的字符串部分。请注意,我假设您不想在第一组之后匹配其他数字:
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
答案 1 :(得分:0)
我猜你可以使用 .find() 字符串方法。
<块引用>find() 方法返回第一次出现的索引 子字符串(如果找到)。如果未找到,则返回 -1。
find() 方法的语法是:
str.find(sub, start, end)
哪里: