python查找指定字符位置_Python 查找字符在字符串中的位置实例

下面为大家分享一篇Python 查找字符在字符串中的位置实例,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

str_1='wo shi yi zhi da da niu '

char_1='i'

nPos=str_1.index(char_1)

print(nPos)

运行结果:7

========是使用find==========

str_1='wo shi yi zhi da da niu '

char_1='i'

nPos=str_1.find(char_1)

print(nPos)

结果:5

========如何查找所有‘i'在字符串中位置呢?===========

#开挂模式

str_1='wo shi yi zhi da da niu '

char_1=str(input('Please input the Char you want:'))

count=0

str_list=list(str_1)

for each_char in str_list:

count+=1

if each_char==char_1:

print(each_char,count-1)

运行结果:

Please input the Char you want:i

i 0

i 1

i 2

i 3

相关推荐:

以上就是Python 查找字符在字符串中的位置实例的详细内容,更多请关注php中文网其它相关文章!

article_wechat2021.jpg?1111

本文原创发布php中文网,转载请注明出处,感谢您的尊重!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 可以使用字符串的 find() 方法来查找指定字符串Python 字符串位置。例如,如果要查找字符串 "hello" 在字符串 "hello world" 位置,可以使用以下代码: ``` s = "hello world" index = s.find("hello") print(index) ``` 输出结果为 ,表示字符串 "hello" 在字符串 "hello world" 的起始位置为 。如果要查找字符串不存在于原字符串,则 find() 方法会返回 -1。 ### 回答2: 在Python,我们可以使用字符串的内置方法来查找指定的子字符串。 一种方式是使用`find()`方法。该方法会返回子字符串第一次出现的索引位置。如果找不到指定的子字符串,它会返回-1。例如: ```python string = "Hello, World!" index = string.find("World") print(index) # 输出:7 ``` 另一种方式是使用`index()`方法。该方法也会返回子字符串第一次出现的索引位置,但如果找不到指定的子字符串,它会抛出一个`ValueError`异常。例如: ```python string = "Hello, World!" index = string.index("World") print(index) # 输出:7 ``` 还有一种更简洁的方式是使用`in`关键字。可以直接使用`in`关键字检查子字符串是否存在于原字符串。例如: ```python string = "Hello, World!" result = "World" in string print(result) # 输出:True ``` 以上是一些常用的方法来在Python字符串查找指定的子字符串。根据具体的需求可以选择使用适合的方法。 ### 回答3: 在Python,我们可以使用`index()`和`find()`这两个方法来查找指定字符串字符串位置。 `index()`方法返回指定字符串字符串首次出现的位置,如果指定字符串不存在,则会抛出ValueError异常。例如,我们有一个字符串s = "Hello, world!",我们可以使用`s.index("world")`来查找"world"在s位置。如果"world"存在于s,则返回值为6。 `find()`方法与`index()`类似,它也返回指定字符串字符串首次出现的位置。但是,如果指定字符串不存在,则返回-1而不会抛出异常。所以,如果我们使用`s.find("world")`来查找"world"在s位置,如果"world"存在于s,则返回值为6;如果"world"不存在于s,则返回值为-1。 下面是一个实例代码,演示了如何在Python字符串查找指定字符串: ```python s = "Hello, world!" target = "world" # 使用index()方法查找指定字符串 try: index = s.index(target) print(f"{target}在{s}位置为:{index}") except ValueError: print(f"{target}在{s}不存在") # 使用find()方法查找指定字符串 index = s.find(target) if index >= 0: print(f"{target}在{s}位置为:{index}") else: print(f"{target}在{s}不存在") ``` 输出结果为: ``` world在Hello, world!位置为:7 world在Hello, world!位置为:7 ``` 这样,我们就可以使用`index()`和`find()`方法来在Python字符串查找指定字符串了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值