)从下标 0 开始索引,找出单词“welcome” 在字符串“Hello, welcome to python world.” 中出现的位置,找不到返回 -1。最后将字符串转换为列表打印出来。
时间: 2024-09-10 21:04:13 浏览: 25
首先,我们需要在给定的字符串 "Hello, welcome to python world." 中查找单词 "welcome" 的位置。由于单词可能是大小写混合的形式,我们先将其转为小写以进行比较。如果找到,返回其起始索引;如果没有找到,则返回 -1。
```python
input_string = "Hello, welcome to python world."
target_word = "welcome"
lowered_input = input_string.lower()
target_word_lower = target_word.lower()
index = lowered_input.find(target_word_lower)
if index != -1:
print(f"单词 'welcome' 出现的位置: {index}")
else:
print("单词 'welcome' 未找到")
# 转换字符串为列表并打印
words_list = lowered_input.split()
print("字符串转换为列表: ", words_list)
```
在这段代码中,`find()` 方法用于查找目标词在字符串中的位置。如果找到了,它会返回词的第一个字符的索引,否则返回 -1。之后我们将字符串通过 `split()` 方法分割成单词列表,并打印出来。
相关问题
从下标 0 开始索引,找出单词 “welcome” 在字符串“Hello, welcome to my world.” 中出现的位置,找不到返回 -1的代码
int index = -1;
String str = "Hello, welcome to my world.";
String keyword = "welcome";
String[] words = str.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].equals(keyword)) {
index = i;
break;
}
}
System.out.println(index); // 输出 1
帮我使用Python实现如下要求:从下标 0 开始索引,找出单词 “welcome” 在字符串“Hello, welcome to my world.” 中出现的位置,找不到返回 -1
好的,以下是使用Python实现的代码:
```python
string = "Hello, welcome to my world."
word = "welcome"
if word in string:
position = string.index(word)
print(position)
else:
print(-1)
```
输出结果为:`7`,表示单词 "welcome" 在字符串中出现的位置是从下标 7 开始。如果找不到该单词,输出结果为 `-1`。