编写一个函数,该函数接受不带空格的字符串参数,在字符串中搜索元音(字母“ a”,“ e”,“ i”,“ o”,“ u”),并替换为大写字符,并打印出带有大写字母的新字符串,并从函数中返回新字符串。您应该使用
isalpha
验证它是一个字符串参数(因此不允许使用空格!),如果不允许则返回一个错误(错误消息应带有“ Error:”)。例如,如果字符串输入为“其他”,则您的程序将输出并返回“ mIscEllAnEOUs”。 如果字符串中的任何字符都不是元音,请打印“没有任何转换!”并返回
None
。
到目前为止,这是我正在使用的,但是我在作业中用粗体显示的部分遇到了麻烦。
def uppercase(word):
vowels = "aeiou"
error_msg = "Error: not a string."
nothing_msg = "Nothing to convert!"
new_word = []
for letter in word:
if word.isalpha():
if letter in vowels:
new_word.append(letter.upper())
else:
new_word.append(letter.lower())
else:
print(error_msg)
return None
new_word = ''.join(new_word)
return new_word
答案 0 :(得分:1)
要检查字符串是否全部为字母,可以使用inFile
。要检查是否包含元音,可以在outFile
中使用生成器表达式来确认至少一个字母是元音。最后,您可以使用cell(f,13)
中的另一个生成器表达式进行转换,以仅使元音大写,然后返回一个新字符串。
cell(f,17)
示例
Sub Update_file()
Dim FolderName As Double
Dim data1, data2, IfExist, inFile, outFile As String
Dim f As Integer
Dim LineNumber As Long
f = 2
LineNumber = 0
Do Until IsEmpty(Cells(f, 2))
IfExist = "L:\" & Cells(f, 2) & "\COMPANY.bat"
If Not Dir(IfExist) = "" Then
inFile = "L:\" & Cells(f, 2) & "\COMPANY.bat"
Open inFile For Input As #1
outFile = "L:\" & Cells(f, 2) & "\COMPANY_NEW.bat"
Open outFile For Output As #2
If Not IsEmpty(Cells(f, 11)) Then
LineNumber = LineNumber + 1
If LineNumber = Cells(f, 13) Then
'aaa:
data2 = Cells(f, 17)
Print #2, data2
LineNumber = LineNumber + 1
GoTo bbb
Else
Do Until EOF(1) Or Cells(f, 13) = LineNumber
'bbb:
Debug.Print LineNumber
Line Input #1, data1
data2 = Trim(data1)
Print #2, data2
LineNumber = LineNumber + 1
If LineNumber = Cells(f, 13) Then
GoTo aaa
End If
Loop
End If
End If
LineNumber = 0
Close #1
Close #2
Else: MsgBox "äçáøä " & Mid(inFile, 4, 5) & " ìà ÷ééîú"
End If
f = f + 1
Loop
End Sub
答案 1 :(得分:0)
除了CoryKramer回答的问题之外,只需给出一种不同的方法,您可以使用python re
模块:
import re
def uppercase(word):
if not word.isalpha():
return 'Error'
if not any(letter in 'aeiou' for letter in word.lower()):
return 'Nothing to convert!'
return re.sub(r'[aeiou]', lambda m: m.group().upper(), word)
我认为这更加简洁。