[英]how to generalize the given code for all strings in python?
What my aim is that writing a function takes a string as an argument such as "Nisa" and returns "N1I2S3A".我的目标是编写 function 将字符串作为参数,例如“Nisa”并返回“N1I2S3A”。 But the code that I have written is only works for strings that have only three characters.
但是我写的代码只适用于只有三个字符的字符串。 How do I generalize the code for all strings?
如何概括所有字符串的代码? If you can help me, I would be really grateful since I am a beginner in python.
如果你能帮助我,我将非常感激,因为我是 python 的初学者。 Here is the code:
这是代码:
tested_str = str(input("Enter a name: "))
def strPattern(mystr):
while tested_str:
if len(mystr) == 1:
return mystr.upper()
else:
return (mystr[0] + str("1") + mystr[1:len(mystr) - 1:1].upper() + str("2")
+ mystr[-1]).upper()
strPattern(mystr=tested_str)
Here is truly pythonic way:)这是真正的pythonic方式:)
tested_str = str(input("Enter a name: "))
def str_pattern(mystr):
return ''.join([f'{c}{i}' for i, c in enumerate(mystr.upper(), 1)])
str_pattern(tested_str)
This could help I believe.这可以帮助我相信。
tested_str = str(input("Enter a name: "))
def strPattern(mystr):
output=[]
for i,c in enumerate(mystr):
if i != 0:
output.append(str(i))
output.append(c.upper())
return "".join(output)
print(strPattern(mystr=tested_str))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.