jupte里Find all occurrences of a substring in a given string by ignoring the case
时间: 2024-10-11 10:16:50 浏览: 25
在Jupyter Notebook中,如果你想在一个给定的字符串中查找忽略大小写的子串的所有出现,你可以使用Python内置的`re`模块(正则表达式库)。下面是一个简单的函数,它会接收一个主字符串`main_str`和一个子串`substring`,然后返回所有匹配项的列表:
```python
import re
def find_substring_occurrences(main_str, substring):
pattern = re.compile(substring, re.IGNORECASE) # 创建正则表达式模式并忽略大小写
matches = pattern.findall(main_str) # 查找所有匹配项
return matches
# 示例用法
main_str = "Hello, hello, Hello World!"
substring = "hello"
occurrences = find_substring_occurrences(main_str, substring)
print("Substring occurrences:", occurrences)
```
在这个例子中,`re.IGNORECASE`标志告诉正则表达式在搜索时不区分大小写。`pattern.findall()`会找到所有非重叠的匹配,并返回它们作为一个列表。
相关问题
# Task 5: Replace all occurrences of 9 Write a Python program that replace all occurrences of 9 with nine for the given string. Sample data : "They ate 9 apples and 9 oranges" Sample output :"They ate nine apples and nine oranges"
Here's the Python code to replace all occurrences of 9 with nine in a given string:
```python
# Input string
input_string = "They ate 9 apples and 9 oranges"
# Replacing all 9's with 'nine'
output_string = input_string.replace('9', 'nine')
# Output string
print(output_string)
```
Output:
```
They ate nine apples and nine oranges
```
In this code, we first define the input string `"They ate 9 apples and 9 oranges"`. Then we use the `replace()` method to replace all the occurrences of `9` with the string `nine`. Finally, we print the output string `"They ate nine apples and nine oranges"`.
String - count the frequency of characters in a string Given a string S, count the frequency of characters in the string S (the occurrences of a character present in the string) Input: hello world where: First-line represents the input string Output: d 1 e 1 h 1 l 3 o 2 r 1 w 1 Explanation: Print the count of each distinct letter present in string S. Assumptions: String contains only lower case letters Length of string S can be 0 to 10000
Here's a sample code in Java that takes in a string input and outputs the frequency of characters in the string:
```java
import java.util.*;
public class FrequencyCounter {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String s = sc.nextLine();
int[] freq = new int[26]; // assuming only lower case letters
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
freq[c - 'a']++; // increment the frequency of the character
}
// print the frequency of each character
for (int i = 0; i < 26; i++) {
if (freq[i] > 0) {
System.out.println((char) ('a' + i) + " " + freq[i]);
}
}
}
}
```
Sample input/output:
```
Enter a string: hello world
d 1
e 1
h 1
l 3
o 2
r 1
w 1
```
阅读全文