gpt4 book ai didi

python - 有没有什么方法可以在字符串之间添加而不将字符串更改为列表 - 或者字符串是不可变的?

转载 作者:太空宇宙 更新时间:2023-11-03 16:55:36 24 4
gpt4 key购买 nike

我是Python初学者,正在做一些简单的问题。但是,我遇到了以下问题:

Define a simple "spelling correction" function correct() that takes a string and sees to it that:

1) two or more occurrences of the space character is compressed into one, and

2) inserts an extra space after a period if the period is directly followed by a letter. E.g. correct("This (multiple spaces) is (multiple spaces) very funny (multiple spaces) and (multiple spaces) cool.Indeed!") should return "This is very funny and cool. Indeed!"

Tip: Use regular expressions!

这是我的代码:

def correct(x):
y = x.split()
y = list(y)
for i in y:
if i == " ":
for o in y:
if o == " ":
y.remove(o)
y.insert(y.index(i)," ")
if i == ".":
y.insert(y.index(i)+1," ")
y = " ".join(y)
return y

print(correct("This is very funny and cool.Indeed!"))

当我运行该程序时,没有任何输出。我不知道我做错了什么。是否有其他方法可以在字符串之间添加而不将字符串更改为列表?或者字符串是不可变的?

最佳答案

@ John La Rooy,也许你的代码更短......我认识自己,我没有看到你的答案,我不会完成......,你是主人......

def correct(s):
s = raw_input("Please give a sentece: ")
return " ".join(s.replace(".", ". ").split())
print correct('s')

关于python - 有没有什么方法可以在字符串之间添加而不将字符串更改为列表 - 或者字符串是不可变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35444847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com