0

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)
Nisa Aslan
  • 37
  • 4

3 Answers3

3

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)
scythargon
  • 3,363
  • 3
  • 32
  • 62
  • I doesn't seem to work because your code works like this (nisa --> N1I2S3A4). What my aim is (nisa --> N12S3A) – Nisa Aslan Apr 05 '21 at 14:23
  • 1
    @NisaAslan strings are sequences, so if you dont want the last char, you can just use `[:-1]` to take all chars except the last one – Chris Doyle Apr 05 '21 at 14:29
0
  • 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.
wwii
  • 23,232
  • 7
  • 37
  • 77
0

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))
  • This should be simple to understand, but I think the previous answer from @scythargon is better (more pythonic) way to do it, you just need to use `[:-1]` to the final string as mentioned in one of the comments. – Alan Abraham Apr 05 '21 at 14:39
  • Your code is more understandable. Thank you again. – Nisa Aslan Apr 05 '21 at 14:54