How to delete a character from a string using Python

前端 未结 16 1379
耶瑟儿~
耶瑟儿~ 2020-11-22 16:35

There is a string, for example. EXAMPLE.

How can I remove the middle character, i.e., M from it? I don\'t need the code. I want to know:

相关标签:
16条回答
  • 2020-11-22 17:34

    Here's what I did to slice out the "M":

    s = 'EXAMPLE'
    s1 = s[:s.index('M')] + s[s.index('M')+1:]
    
    0 讨论(0)
  • 2020-11-22 17:35

    To delete a char or a sub-string once (only the first occurrence):

    main_string = main_string.replace(sub_str, replace_with, 1)
    

    NOTE: Here 1 can be replaced with any int for the number of occurrence you want to replace.

    0 讨论(0)
  • 2020-11-22 17:37
    from random import randint
    
    
    def shuffle_word(word):
        newWord=""
        for i in range(0,len(word)):
            pos=randint(0,len(word)-1)
            newWord += word[pos]
            word = word[:pos]+word[pos+1:]
        return newWord
    
    word = "Sarajevo"
    print(shuffle_word(word))
    
    0 讨论(0)
  • 2020-11-22 17:39

    How can I remove the middle character, i.e., M from it?

    You can't, because strings in Python are immutable.

    Do strings in Python end in any special character?

    No. They are similar to lists of characters; the length of the list defines the length of the string, and no character acts as a terminator.

    Which is a better way - shifting everything right to left starting from the middle character OR creation of a new string and not copying the middle character?

    You cannot modify the existing string, so you must create a new one containing everything except the middle character.

    0 讨论(0)
提交回复
热议问题