简体   繁体   中英

Finding specific characters within a string

I'm attempting to find all vowels within a string to replace them.

Here is what I've been working with:

word = "abcde"
vowels = "aeiou"
v = list(vowels)
hey = False
for i in range(len(word)):
    if word[i] == v:
        hey = True
print hey

I was trying to replace all those positions with strings with the symbol "$", but I can't figure out how I can do this linear search properly.

Under the assumption that this is for an assignment/class of some sort, here is a simple example. You can iterate through a string by character, so this goes through each letter in your vowel set and replaces each instance in your word with the $ character:

In [33]: s = 'abcde'

In [34]: for c in 'aeiou':
   ....:     s = s.replace(c, '$')
   ....:
   ....:

In [35]: s
Out[35]: '$bcd$'

And keeping it simple, to do it in reverse:

In [6]: s = 'abcde'

In [7]: replace = ''

In [8]: for c in s:
   ...:     if c not in 'aeiou':
   ...:         replace += c
   ...:
   ...:

In [9]: for c in replace:
   ...:     s = s.replace(c, '$')
   ...:
   ...:

In [10]: s
Out[10]: 'a$$$e'

This doesn't get into a lot of other very cool functions which can handle this in one/two lines, but hopefully will serve as a building block :)

"".join(("$" if char in vowels else char) for char in string)

Using a regular expression is probably the easiest:

(?i) means do case insensitive comparisons
[aeiou] means any of a, e, i, o, or u

The rest is fairly obvious

import re

s = 'alpha beta charlie delta echo foxtrot golf hotel'
print re.sub('(?i)[aeiou]', '$', s)
# $lph$ b$t$ ch$rl$$ d$lt$ $ch$ f$xtr$t g$lf h$t$l

Either that, or str.translate :

from string import maketrans

to_dollar = 'aeiouAEIOU'
trans = maketrans(to_dollar, '$' * len(to_dollar))
print s.translate(trans)
# $lph$ b$t$ ch$rl$$ d$lt$ $ch$ f$xtr$t g$lf h$t$l

Either that, or using a dict :

lookup = dict.fromkeys('aeiouAEIOU', '$')
print ''.join(lookup.get(c, c) for c in s)
# $lph$ b$t$ ch$rl$$ d$lt$ $ch$ f$xtr$t g$lf h$t$l

You can use a set to quickly determine if the character you are iterating over is a vowel. The set object (usually) has constant look-up time instead of linear look-up time like a list.

vowels = set(vowels)
''.join('$' if ch in vowels else ch for ch in string)
word = "a quick brown fox"
vowels = list("aeiou")
hey = False
for w in word:
    hey = hey or w in vowels

print hey

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM