嗨,我刚刚开始学习python。如何替换字符串中的字符



这是字符串"你在哪里?在钟楼附近等我">

现在总共有9个单词。我必须考虑3对,每对包含从字符串开始的3个连续单词

事情是这样的,我必须将第一个单词中的元音替换为"%">,第二个单词中的辅音带有"strong>"#",最后一个单词必须转换为大写。它们应该相互连接。

输出应该是这样的Wh%r%a#eYOU?M%%t#e第%##o##塔。

以下是我尝试过的

def replaceVowelsWithK(s1, K):
vow = 'AEIUOaeiou'
for ele in vow:
s1 = s1.replace(ele, K)
return s1

def replaceConsWithX(s2, x): 
cons = "bcdfghjklmnpqrstvwxyz"
for con in cons:
s2= s2.replace(con, "#")
return s2

def replaceVowelsWithK(s4, K):
vow = 'AEIUOaeiou'
for ele in vow:
s4 = s4.replace(s4, K)
return s4


def replaceConsWithX(s5, x): 
cons = "bcdfghjklmnpqrstvwxyz"
for con in cons:
s5= s5.replace(con, "#")
return s5
def replaceVowelsWithK(s7, K):
vow = 'AEIUOaeiou'
for ele in vow:
s7 = s7.replace(ele, K)
return s7

def replaceConsWithX(s8, x): 
cons = "bcdfghjklmnpqrstvwxyz"
for con in cons:
s8= s8.replace(con, "#")
return s8

s1 = "Where"
s2="are"
s3='you?'
s4="Meet"
s5="me"
s6="near"
s7="the"
s8="clock"
s9="tower"
K="%"
x="#"
x1=replaceVowelsWithK(s1, K)
x2=replaceConsWithX(s2, x)
x3=s3.upper()
x4=replaceVowelsWithK(s4, K)
x5=replaceConsWithX(s5, x)
x6=s6.upper()
x7=replaceVowelsWithK(s7, K)
x8=replaceConsWithX(s8, x)
x9=s9.upper()
result=x1+x2+x3+x4+x5+x6+x7+x8+x9
print(result)

代码太长。我只需要有一个单一的输入字符串";你在哪里?在钟楼附近等我"有简单的方法吗?比如拆分字符串并为子字符串使用公共函数?

st = "Where are you? Meet me near the clock tower"
ls = st.split()
word = ""
for i in range(len(ls)):
if i%3 == 0:
t = ls[i]
for j in "aeiou":
t = t.replace(j, "%")
word += t
elif i%3 == 1:
t = ls[i]
for j in "bcdfghjklmnpqrstvwxyz":
t = t.replace(j, "#")
word += t
else:
word += ls[i].upper()
print(word)

尝试将字符串拆分成一个列表,然后根据列表更改单词。

最新更新