Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中迭代字符串时,如何引用字符串中的不同字符?_Python_String - Fatal编程技术网

在Python中迭代字符串时,如何引用字符串中的不同字符?

在Python中迭代字符串时,如何引用字符串中的不同字符?,python,string,Python,String,我正在尝试编写一个脚本,它可以使用两个字母(aa或tt),然后将它们改为该字母,后跟ː,长度符号(aa将变成aː,而tt将变成tː)。我想通过迭代字符串来实现这一点,并用ː替换字符串中与上一个相同的任何字符。如何做到这一点?您可以尝试类似的方法。我反复浏览字符串,并对照前一个字母检查每个字母。如果匹配,则执行替换;如果不匹配,则继续执行替换,并将新的上一个字母存储在上一个字母中。此外,我还使用.lower()方法处理字母,即使一个字母大写,另一个字母不大写 string = "Tthis is

我正在尝试编写一个脚本,它可以使用两个字母(
aa
tt
),然后将它们改为该字母,后跟
ː
,长度符号(
aa
将变成
,而
tt
将变成
)。我想通过迭代字符串来实现这一点,并用
ː替换字符串中与上一个相同的任何字符。
如何做到这一点?

您可以尝试类似的方法。我反复浏览
字符串
,并对照前一个字母检查每个字母。如果匹配,则执行替换;如果不匹配,则继续执行替换,并将新的上一个字母存储在
上一个字母中。此外,我还使用
.lower()
方法处理字母,即使一个字母大写,另一个字母不大写

string = "Tthis is a testt of the ddouble letters"

previousletter = string[0]

for letter in string:
    if letter.lower() == previousletter.lower():
       string = string.replace("%s%s" % (previousletter, letter) , "%s:" % (letter))
    previousletter = letter

print(string)
以下是输出:

t:his is a test: of the d:ouble let:ers

我希望这会有所帮助,并且可以自由地就我使用的代码提出任何问题。快乐编程

字符串具有
.replace
方法。