Remove specific characters from a string

前端 未结 2 1922
清酒与你
清酒与你 2020-12-21 12:11

I want to remove all vowels from a string that the user gives. Below is my code and what I get as an output. For some reason the for loop is only checking the first characte

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-21 12:43

    You can't remove characters from a string: a string object is immutable. All you can do is to create a new string with no more wovels in it.

    x = ' Hello great world'
    print x,'  id(x) == %d' % id(x)
    
    y = x.translate(None,'aeiou') # directly from the docs
    print y,'  id(y) == %d' % id(y)
    
    z = ''.join(c for c in x if c not in 'aeiou')
    print z,'  id(z) == %d' % id(z)
    

    result

     Hello great world   id(x) == 18709944
     Hll grt wrld   id(y) == 18735816
     Hll grt wrld   id(z) == 18735976
    

    The differences of addresses given by function id() mean that the objects x, y, z are different objects, localized at different places in the RAM

提交回复
热议问题