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

2024-09-30 16:32:00 发布

您现在位置:Python中文网/ 问答频道 /正文

这是字符串“你在哪里?在钟楼附近等我。”

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

问题是,我必须将第一个单词的元音替换为“%”,第二个单词的辅音替换为“#”,最后一个单词必须转换为大写。它们应该相互连接

输出应该如下所示 Wh%r%a#eYOU?M%%t#eNEARth%%o#o#TOWER

这是我试过的

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)

代码太长了。 我只需要一个输入字符串“你在哪里?在钟楼附近等我。” 有没有一个简单的方法可以做到这一点?比如拆分字符串并对子字符串使用公共函数


Tags: inforreturndefconreplaces4s2
1条回答
网友
1楼 · 发布于 2024-09-30 16:32:00
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)

尝试将字符串拆分为列表,然后根据列表更改单词

相关问题 更多 >