简体   繁体   English

有没有一种方法可以比较字符串中的字符。 蟒蛇?

[英]Is there a way to compare characters in a string via. python?

I am wondering if there is a way that I can compare the first letter of the string to the second; 我想知道是否有一种方法可以比较字符串的第一个字母和第二个字母; then the third to the forth ... etc. At the moment I have this: 然后是第三到第四...等等。目前我有这个:

a=0
b=0
string = "GG EZ"
if string[a:b] == string[a+1:b+1]:
    print("hello")

It works but is there a more efficient way of doing it? 它有效,但是有更有效的方法吗?

You can use zip to pair up the elements 您可以使用zip配对元素

s = "GGEZ"
for a, b in zip(*[iter(s)]*2):
    if a==b:
        print('Hello')

More on this usage of zip here 此处更多有关zip用法

string = "GG EZ abbdff"

for i in range(0, len(string), 2):
    if string[i] == string[i+1]:
        print("characters match")

Create a range of every second character in the string. 在字符串中每隔两个字符创建一个范围。 Iterate over the range and compare character at the index i with the following. 遍历该范围,并将索引i处的字符与以下字符进行比较。

Edit: If your string length is an odd number you run into an out of range exception. 编辑:如果您的字符串长度是一个奇数,则会遇到超出范围的异常。 I let you figure that one out by yourself :) 我让你自己弄清楚那一个:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM