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

我知道您这样做是为了学习语言,但您应该知道您可以简单地使用该方法sub替换为正则表达式:

import re
re.sub('[aeiou]', '$', aString)
于 2012-05-11T16:24:04.593 回答
2
strs="abcduitryd"
print("".join(('$' if x in 'aeiou' else x for x in strs)))

$bcd$$tryd

或者:

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

$bcd$$tryd

或者 :

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 回答
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] = '$'

但是使用替换方法可能会更容易。

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 回答
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 回答
1

“Pythonic”方式是对字符串使用 translate 方法。
例子:

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 回答