python和连接混淆

python和连接混淆,python,Python,问题:编写一个函数,该函数将从一个参数返回一个国家代码字符串,该参数是一个价格字符串(在国家代码后包含美元金额)。您的函数将采用一系列价格作为参数,如下所示:“US$40,AU$89,JP$200”。在本例中,函数将返回字符串“US,AU,JP” 提示:您可能希望将原始字符串拆分为一个列表,操作各个元素,然后再次将其转换为字符串 输入: def get_country_codes(prices): values = "" price_codes = prices.split(',

问题:编写一个函数,该函数将从一个参数返回一个国家代码字符串,该参数是一个价格字符串(在国家代码后包含美元金额)。您的函数将采用一系列价格作为参数,如下所示:“US$40,AU$89,JP$200”。在本例中,函数将返回字符串“US,AU,JP”

提示:您可能希望将原始字符串拆分为一个列表,操作各个元素,然后再次将其转换为字符串

输入:

def get_country_codes(prices):
    values = ""
    price_codes = prices.split(',')
    for price_code in price_codes:
        values = value + price_code.strip()[0:2])

    return values


list1 = [ , ]

print(get_country_codes("NZ$300, KR$1200, DK$5").join(list1))
试试这个:

codes="NZ$300, KR$1200, DK$5"
get_country_codes=lambda c: ', '.join(e[0:2] for e in c.split(", "))
get_country_codes(codes)

由于一些现有货币有三个字母的符号,例如
CAD
,因此我们必须在任何金额之前预期未知数量的字符

def get_countries(s):
    countries = [c.split('$')[0] for c in s.split(',')]
    return ','.join(countries)

s = "US$40, AU$89, JP$200, CAD$15"

print(get_countries(s))
输出 或者,您可以使用
re
简单地删除字符串中国家代码后面的任何内容

import re

s = "US$40, AU$89, JP$200, CAD$15"
countries = re.sub('\W\d+', '', s)

print(countries)

这不是一个编码服务网页,带着特定的问题和代码返回,显示一些努力。为什么不简单地使用def,这里不需要lambda
import re

s = "US$40, AU$89, JP$200, CAD$15"
countries = re.sub('\W\d+', '', s)

print(countries)