0

私は自分自身にPythonを教えようとしていて、それを使っていくつかの厄介なタスクを実行しています。その瞬間、私はリストと文字列を扱っています。文字列は不変であることがわかっているので、文字列をリストに変換し、リストをループして母音を$記号に変更したいと思います。問題は、$記号が母音に起因していないことです。これが私のコードです:

aString = raw_input("Please enter a sentence: ")

aString = list(aString)

for i in xrange(len(aString)):
    if i=='a' or \
       i=='e' or \
       i=='i' or \
       i=='o' or \
       i=='u':
        i.newattribute = '$'

print aString
4

5 に答える 5

4

I know you are doing it to learn the language, but you should know you could simply use the method sub to substitute with a regular expression:

import re
re.sub('[aeiou]', '$', aString)
于 2012-05-11T16:24:04.593 に答える
2

次のことを行います。

for i in xrange(len(aString)):
    if aString[i]=='a' or \
       aString[i]=='e' or \
       aString[i]=='i' or \
       aString[i]=='o' or \
       aString[i]=='u':
          aString[i] = '$'

ただし、replaceメソッドを使用する方がおそらく簡単です。

replaceList = ['a', 'e', 'i', 'o', 'u']
aString = raw_input("Please enter a sentence: ")
for letter in replaceList:
    aString.replace(letter)
print aString
于 2012-05-11T16:14:58.430 に答える
2
strs="abcduitryd"
print("".join(('$' if x in 'aeiou' else x for x in strs)))

$bcd$$tryd

or:

strs="abcduitryd"
lis=list(strs)
for i,x in enumerate(lis):
    if x in 'aeiou':
        lis[i]='$'
strs="".join(lis)
print(strs)

$bcd$$tryd

or :

strs="abcduitryd"
for i,x in enumerate(strs):
    if x in 'aeiou':
        strs=strs.replace(strs[i],'$')
print(strs)

$bcd$$tryd
于 2012-05-11T16:20:35.317 に答える
1

The "Pythonic" way is to use the translate method for string.
example:

import string
mystr="hello world"
vowels="aeiou"
token="$"*len(vowels)
tab=string.maketrans(vowels,token)
mystr.translate(tab)
'h$ll$ w$rld'
于 2012-05-11T16:42:29.517 に答える
1

If you are learning python, one cool feature that can be used is a list comprehension. You can do this:

>>> str = "hello world"
>>> l = ["$" if ch in "aeiou" else ch for ch in str]
>>> str = "".join(l)
>>> str
'h$ll$ w$rld'

The second line builds a list, walking through each character and applying `"$" if ch in "aeiou" else ch1 to it. You then just join the list to get a new string. It's doing exactly what you are trying to do, converting the string to a list and in the process, coverting vowels to '$'.

This is not the most efficient way to do it of course. The best way to do it is to use a library meant for this sort of thing as others have mentioned.

于 2012-05-11T16:43:24.267 に答える