如何从sting中选择单个字符并用另一个[Python3]替换它们?

2024-06-01 23:26:00 发布

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

例如:

aStr = input("Please input: ")

把aStr中所有的A字符变成4个字符,或者把A变成@etc的东西。 (我在这里用什么?我知道string.stripstring.translate似乎有两个参数,但只解决了一个,这有点超出我的理解。。。我是个新手)。你知道吗

print("Your output is: " +aStr)

Tags: inputoutputyour参数stringisetc字符
3条回答

string.replace()在python3.x中不推荐使用,因此可以使用str.replace()re.sub()

使用replace比使用regex更简单,对于大多数简单的使用场景来说都很好。你知道吗

aStr = input("Please input: ")

print("Your output is: " + aStr.replace("A","@@@@"))

如果要更改大写或小写A/A

aStr = input("Please input: ")

if "A" in aStr:
    print("Your output is: " + aStr.replace("A","@@@@"))
elif "a" in aStr:
    print("Your output is: " + aStr.replace("a","@@@@"))

一个string对象有一个replace方法。你可以这样做:

>>> x = 'Hello world'
>>> x.replace('l', '@')
'He@@o wor@d'

>>> help(str.replace)
Help on method_descriptor:

replace(...)
    S.replace(old, new[, count]) -> str

    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.

您还可以通过索引访问单个字符,如x[0],但请注意,字符串在Python中是不可变的,因此您不能为字符赋值。你知道吗

>>> x[0]='p'
                                     -
TypeError                                 Traceback (most recent call last)
<ipython-input-5-2cb5a895cce7> in <module>()
  > 1 x[0]='p'

TypeError: 'str' object does not support item assignment

编辑:每隔出现一次就替换一次有点棘手,目前我想不出一个好的一行,但是这个详细和稍微不pythonic的函数可以:

import re

def replace_every_nth(mystring, oldstr, newstr, nth):
    parts = re.split('(%s)' % oldstr, mystring)
    partcount = 1
    for i in range(len(parts)):
        if parts[i] == oldstr:
            if partcount % nth == 0:
                parts[i] = newstr
            partcount += 1
    return ''.join(parts)

>>> replace_every_nth(x, 'l', '@', 1)
'He@@o wor@d'

>>> replace_every_nth(x, 'l', '@', 2)
'Hel@o world'

>>> replace_every_nth(x, 'l', '@', 3)
'Hello wor@d'

>>> replace_every_nth(x, 'll', '@', 3)
'Hello world'

>>> replace_every_nth(x, 'll', '@', 1)
>>> 'He@o world'

>>> replace_every_nth(x, 'lll', '@', 1)
>>> 'Hello world'

相关问题 更多 >