python - Python:如何用@符号替换字符串中的元音
问题描述
我有一个关于用符号“@”替换元音(aeiou 上/下)的问题。我写了一个完整的代码,它也只打印大写字母(工作)、字符串中的每个其他字符(工作)和字符串中的位数(工作)。我在程序中遇到的唯一问题是我无法用符号“@”替换字符串中的所有元音,也无法输出字符串中每个元音的位置。我在 Python 的低级编码课程中,所以我只使用循环来完成程序。这是我到目前为止所拥有的:
str=input("Enter a string: ")
char=0
s=0
onlyCaps=0
v=0
n=0
count=0
countv=0
vowels=('a' and 'A' or 'e' and 'E' or 'i' and 'I' or 'o' and 'O' or 'u' and 'U')
position=vowels
def upperOnly(s):
onlyCaps=""
for char in s:
if char.isupper()==True:
onlyCaps+=char
return onlyCaps
for n in str:
if n.isnumeric():
count=count+1
if str.__contains__(vowels):
countv+=1
print(upperOnly(str))
print(str[::2])
print(str.replace(vowels,'@'))
print("The string contains",count,"digits.")
print("The vowels are at positions:",countv)
输出:
吨
Ti 坐 2。
这是一个测试 123。(字符串应该将元音替换为“@”)
该字符串包含 3 位数字。
元音的位置:0(给出元音的位置)
解决方案
您可以为此使用正则表达式(第三行是重要的,其他只是支持):
import re
line = "My hovercraft is full of ANNOYING eels"
line = re.sub("[aeiou]", "@", line, flags = re.I)
print(line)
这输出:
My h@v@rcr@ft @s f@ll @f @NN@Y@NG @@ls
更详细地解释:
re.sub("[aeiou]", "@", line, flags = re.I)
\_____/ V \__/ \__________/
| | | |
| | | +-- ignore case (change upper and lower).
| | +----------- string to use for input.
| +----------------- string to replace with.
+------------------------- character class to replace (all vowels).
推荐阅读
- spring - Spring 获取请求被拒绝,因为 URL 包含潜在的恶意字符串“;”
- java - 在 RecyclerView 中查找完全可见的项目(如 TikTok 和 Instagram Story)
- javascript - 如何无限查找标签状态?
- c# - Autofac.Core.DependencyResolutionException:类型“”的表达式不能用于 Autofac 6.2 中的返回类型“System.Object”
- dynamics-crm - 删除所有依赖组件后如何删除实体?
- javascript - 地图循环中的onchange更新状态[反应]
- syntax - 语法错误 JAGSUI:解析模型文件时出错
- python - 如何在单个 django 频道视图中创建/添加多个组
- c++ - 如何让数组显示升序和降序
- ruby-on-rails - 没有数据库的自定义属性