str_data = "helloworldhellopythonhelloc++hellojava",请使用Python代码,查找字符串str_data中的所有'hello'字符串的起始下标,并将起始下标打印出来
时间: 2024-05-05 07:20:41 浏览: 19
可以使用字符串的`find()`方法,循环查找所有的'hello'字符串并打印它们的起始下标。示例如下:
```
str_data = "helloworldhellopythonhelloc hellojava"
index = 0
while True:
index = str_data.find('hello', index)
if index == -1:
break
print(index)
index += len('hello')
```
输出结果为:
```
0
10
21
```
其中,第一个'hello'字符串的起始下标为0,第二个为10,第三个为21。
相关问题
str_data = "helloworldhellopythonhelloc++hellojava"
这是一个字符串变量,其中包含了三个子字符串 "helloworld"、"hellopython" 和 "hellojava",它们之间用空格分隔。您可以通过字符串的 split() 方法将其拆分成一个字符串列表:
```
str_data = "helloworldhellopythonhelloc hellojava"
str_list = str_data.split()
print(str_list)
```
输出:
```
['helloworldhellopythonhelloc', 'hellojava']
```
您还可以使用正则表达式来匹配其中的子字符串,比如:
```
import re
str_data = "helloworldhellopythonhelloc hellojava"
str_list = re.findall(r'hello\w+', str_data)
print(str_list)
```
输出:
```
['helloworld', 'hellopython', 'hellojava']
```
这里使用了正则表达式 `hello\w+` 来匹配以 "hello" 开头,后面跟着任意字母或数字的子字符串。
设定字符串test_str ="02101 Hello JYCJ Python 2012",去掉test_str中两侧的数字和空格后输出。
可以使用字符串的strip()方法去掉两侧的空格,然后再使用isdigit()方法判断是否为数字,最后使用字符串的切片操作去掉数字即可。
代码如下:
```python
test_str = "02101 Hello JYCJ Python 2012"
trimmed_str = test_str.strip() # 去除两侧空格
while trimmed_str[:1].isdigit(): # 判断是否为数字
trimmed_str = trimmed_str[1:]
while trimmed_str[-1:].isdigit():
trimmed_str = trimmed_str[:-1]
print(trimmed_str)
```
输出结果为:
```
Hello JYCJ Python
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)