简体   繁体   中英

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". 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. 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:)

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)
  • iterate over the characters of the string using enumerate
    • start the enumeration at one
  • on each iteration: construct a list by appending the character then the enumeration
  • make a new string by joining the characters in the list.

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM