简体   繁体   English

如何概括 python 中所有字符串的给定代码?

[英]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)
  • iterate over the characters of the string using enumerate使用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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Python 中概括此代码? - How can I generalize this code in Python? 泛化python脚本以在目录中的所有文件上运行 - generalize python script to run on all files in a directory Python搜索代码中的所有字符串 - Python search for all strings in code 如何在python中的给定html代码中获取所有td值 - how to get all td values inside given html code in python 如何概括所有字母数字字符的 for 循环 - How to generalize a for loop for all alfanumerical characters 如何使用Python从字符串日期列表中获取给定月份的所有日期? - How to get all dates of given month from the list of dates in strings with python? Python:如何找到与给定的多种模式匹配的所有字符串 - Python: How can I find all strings matching any of the multiple patterns given 如何获得一个字符串列表,使其代表给定列表中的所有字符串? - How to obtain a list of strings such that it represents all the strings in a given list? 如何编写 python 代码来计算给定数字的所有组合,这些组合可以求和给定数字? - how to write a python code to calculate all the combination of given numbers that can sum up to a given number? Python:DIY将此“ all_subsets”函数推广为任何大小的子集 - Python : DIY generalize this “all_subsets” function to any size subsets
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM