代码之家  ›  专栏  ›  技术社区  ›  kostia

更改字符串中的一个字符?

  •  293
  • kostia  · 技术社区  · 15 年前

    在Python中,替换字符串中的字符最简单的方法是什么?

    例如:

    text = "abcdefg";
    text[1] = "Z";
               ^
    
    9 回复  |  直到 4 年前
        1
  •  652
  •   scvalex    15 年前

    >>> s = list("Hello zorld")
    >>> s
    ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
    >>> s[6] = 'W'
    >>> s
    ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
    >>> "".join(s)
    'Hello World'
    

    Python字符串是不可变的(即它们不能被修改)。有 a lot 原因是什么。使用列表直到你没有选择,然后将它们转换成字符串。

        2
  •  248
  •   Community PPrice    7 年前

    有三种方法。对于速度搜索者,我推荐“方法2”

    方法1

    answer

    text = 'abcdefg'
    new = list(text)
    new[6] = 'W'
    ''.join(new)
    

    与“方法2”相比,这相当慢

    timeit.timeit("text = 'abcdefg'; s = list(text); s[6] = 'W'; ''.join(s)", number=1000000)
    1.0411581993103027
    

    由此得出 answer

    text = 'abcdefg'
    text = text[:1] + 'Z' + text[2:]
    

    这要快得多:

    timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
    0.34651994705200195
    

    方法3:

    字节数组:

    timeit.timeit("text = 'abcdefg'; s = bytearray(text); s[1] = 'Z'; str(s)", number=1000000)
    1.0387420654296875
    
        3
  •  139
  •   Jochen Ritzel    15 年前
    new = text[:1] + 'Z' + text[2:]
    
        4
  •  44
  •   guntbert Spoike    4 年前

    Python字符串是不可变的,您可以通过复制来更改它们。

    text = "Z" + text[1:]
    

    这个 text[1:] 返回中的字符串 text 从位置1到结尾,位置从0开始计数,因此“1”是第二个字符。

    您可以对字符串的任何部分使用相同的字符串切片技术

    text = text[:1] + "Z" + text[2:]
    

    或者,如果字母只出现一次,您可以使用建议的搜索和替换技术

        5
  •  13
  •   Mahmoud    9 年前

    s = "abcdefg"
    b_s = bytearray(s)
    b_s[1] = "Z"
    s = str(b_s)
    print s
    aZcdefg
    

    编辑:将str更改为s

    edit2:正如两位炼金术士在评论中提到的,此代码不适用于unicode。

        6
  •  8
  •   Community PPrice    7 年前

    正如其他人所说,通常Python字符串应该是不可变的。

    但是,如果您使用的是python.org上的实现CPython,则可以使用ctypes修改内存中的字符串结构。

    下面是一个示例,我使用该技术清除字符串。

    Mark data as sensitive in python

    我提到这一点是为了完整,这应该是你的最后手段,因为它是黑客。

        7
  •  8
  •   Community PPrice    4 年前

    这个密码不是我的。我记不起我在哪里拍的网站表单了。有趣的是,您可以用一个或多个字符替换一个或多个字符。 虽然这个回复已经很晚了,但像我这样的新手(任何时候)可能会发现它很有用。

    更改文本功能。

    mytext = 'Hello Zorld'
    mytext = mytext.replace('Z', 'W')
    print mytext,
    
        8
  •  6
  •   Manoj Kumar S    4 年前

    字符串在Python中是不可变的,这意味着您不能更改现有字符串。 但是如果你想改变其中的任何字符,你可以创建一个新的字符串,如下所示,

    def replace(s, position, character):
        return s[:position] + character + s[position+1:]
    


    //结果:香港

    替换('Dog',10,'s')
    //结果:狗

        9
  •  2
  •   angelcool.net    9 年前

    实际上,使用字符串,可以执行如下操作:

    oldStr = 'Hello World!'    
    newStr = ''
    
    for i in oldStr:  
        if 'a' < i < 'z':    
            newStr += chr(ord(i)-32)     
        else:      
            newStr += i
    print(newStr)
    
    'HELLO WORLD!'
    

    基本上,我将“+”字符串“添加到一个新字符串中:)。

        10
  •  1
  •   OsorioSP    3 年前

    我喜欢f字串:

    text = f'{text[:1]}Z{text[2:]}'
    

    在我的机器中,此方法比使用+连接字符串的“快速方法”快10%:

    >>> timeit.timeit("text = 'abcdefg'; text = text[:1] + 'Z' + text[2:]", number=1000000)
    1.1691178000000093
    >>> timeit.timeit("text = 'abcdefg'; text = f'{text[:1]}Z{text[2:]}'", number =1000000)
    0.9047831999999971
    >>>
    
        11
  •  0
  •   Paul Nathan    5 年前

    ascii/utf-8 (该框中有很多用例):

    b = bytearray(s, 'utf-8')
    # process - e.g., lowercasing: 
    #    b[0] = b[i+1] - 32
    s = str(b, 'utf-8')
    

    python 3.7.3

        12
  •  0
  •   mohammed wazeem    4 年前

    我想添加另一种方法来更改字符串中的字符。

    >>> text = '~~~~~~~~~~~'
    >>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
    '~+~~~~~~~~~'
    

    与将字符串转换为列表并替换第i个值然后再次合并相比,它的速度有多快?。

    列表法

    >>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
    0.8268570480013295
    

    我的解决方案

    >>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
    0.588400217000526
    
        13
  •  0
  •   eapetcho    4 年前

    找到 代替 单行if语句中的方法可以是:

    ```python
    my_var = "stackoverflaw"
    my_new_var = my_var.replace('a', 'o', 1) if my_var.find('s') != -1 else my_var
    print(f"my_var = {my_var}")           # my_var = stackoverflaw
    print(f"my_new_var = {my_new_var}")   # my_new_var = stackoverflow
    ```
    
        14
  •  -2
  •   passionatedevops    3 年前

    试试这个:

    old_string = "mba"
    string_list = list(old_string)
    string_list[2] = "e"
    //Replace 3rd element
    
    new_string = "".join(string_list)
    
    print(new_string)