关于python:使用string.replace(x,y)替换所有

Using string.replace(x, y) to replace all

我刚刚开始学习python,并希望使用string.replace(x,y)。

具体来说,根据字母是否最初大写,将所有内容全部替换为X和x。

例如
John S. Smith - > Xxxx X. Xxxxx

我目前创建的是下面的内容。

1
2
3
4
print("Enter text to translate:", end ="")
sentence = input ()
replaced = sentence.replace("","x")
print(replaced)

但是当我输入像"John Smith"这样的文字时。 我的回复是"xJxoxhxnx xSx.x xSxmxixtxhx"。

先感谢您!

编辑:虽然string.replace(x,y)的执行时间可能更长,但我想在找到执行相同操作的更快更短的方法之前慢慢建立我的知识。 如果用string.replace(x,y)而不是re.sub来解释它,我将非常感激

Edit2:我收到通知,string.replace是错误的工具。 谢谢您的帮助! 我会读到re.sub而不是。


如果你坚持使用replace,即使它是错误的工作工具(因为它一次只能替换一个字母并且每次都必须遍历整个字符串),这里有一种方法:

1
2
3
4
5
6
7
8
9
>>> s = 'John S. Smith'
>>> for c in s:
        if c.islower():
            s = s.replace(c, 'x')
        if c.isupper():
            s = s.replace(c, 'X')

>>> s
'Xxxx X. Xxxxx'

而且有点整齐有效的方式:

1
2
>>> ''.join('x' * c.islower() or 'X' * c.isupper() or c for c in s)
'Xxxx X. Xxxxx'

和正则表达方式:

1
2
>>> re.sub('[A-Z]', 'X', re.sub('[a-z]', 'x', s))
'Xxxx X. Xxxxx'

1
2
3
4
5
import re
print("Enter text to translate:", end ="")
sentence = input()
replaced = re.sub("[A-Z]", 'X', re.sub("[a-z]", 'x', sentence))
print replaced

使用re.sub替换字符串的单个字符或迭代字符串。


平原方式:

1
2
3
4
5
6
7
8
9
10
11
12
>>> my_string ="John S. Smith"
>>> replaced = ''
>>> for character in my_string:
    if character.isupper():
        replaced += 'X'
    elif character.islower():
        replaced += 'x'
    else:
        replaced += character    

>>> replaced
'Xxxx X. Xxxxx'

一个班轮:

1
2
>>> ''.join('x' if c.islower() else 'X' if c.isupper() else c for c in my_string)
'Xxxx X. Xxxxx'

不是字符串替换的正确用法。
你可以做两件事:

  • 循环遍历字符串并执行操作
  • 使用re.sub替换使用正则表达式。 (如何在string.replace中输入正则表达式?)

1
2
3
4
print("Enter text to translate:", end ="")
sentence = input ()
replaced = ''.join(['x' if (i>='a' and i<='z') else 'X' if (i>='A' and i<='Z') else i for i in sentence])
print(replaced)


您可以使用re模块,并为re.sub提供回调函数来实现此目的。

1
2
3
4
5
6
7
8
9
10
11
import re

def get_capital(ch):
    if ch.isupper():
        return"X"
    return"x"

def get_capitals(s):
    return re.sub("[a-zA-Z]", lambda ch: get_capital(ch.group(0)), s)

print(get_capitals("John S. Smith"))

有输出:

1
Xxxx X. Xxxxx

作为一种风格问题,我并没有将这些内容浓缩成lambda或one-liners,尽管你可能会这样做。

这将比重复连接快得多。


**编辑固定代码**

试试这个,这是一个简单易破坏的例子,但这是你需要达到你想要的:

1
2
3
4
5
6
7
8
9
10
11
12
13
s ="Testing This"
r =""

for c in s:
    if c.isalpha():
        if c.islower():
            r +="x"
        else:
            r +="X"
    else:
        r += c

print(r)