gpt4 book ai didi

python - 从字符串更改 int 和 string

转载 作者:行者123 更新时间:2023-12-03 23:11:46 25 4
gpt4 key购买 nike

format_address 函数将地址字符串的一部分分离为新字符串:house_number 和 street_name,并返回:“名为 Y 的街道上的房屋编号 X”。输入字符串的格式为:数字门牌号,后跟街道名称,其中可能包含数字,但不能单独包含数字,并且可能有几个字长。例如,“123 Main Street”、“1001 1st Ave”或“55 North Centre Drive”。填补空白以完成此功能。

def format_address(address_string):
# Declare variables
house_number=' '
street_name=" "

# Separate the address string into parts
x=address_string.split(" ")
# Traverse through the address parts
for y in x:
if(y.isdigit()):
house_number=y
else:
street_name+=y
street_name+=' '
# Determine if the address part is the
# house number or part of the street name
# Does anything else need to be done
# before returning the result?

# Return the formatted string
return "house number {} on street named {}".format(house_number,street_name)

print(format_address("123 Main Street"))
# Should print: "house number 123 on street named Main Street"

但它显示输出为:
house number 123 on street named  
house number 1001 on street named
house number 55 on street named

最佳答案

当您使用 str.split() ,您可以选择要将字符串拆分为多少段(只要不超过最大值)。在您的情况下,字符串应该只拆分一次,以将门牌号与街道名称分开。此外,您可以格式化字符串:

def format_address(address_string):
num, st = address_string.split(' ',1)
return f"house number {num} on street named {st}"

print(format_address("123 Main Street"))

输出:
house number 123 on street named Main Street

关于python - 从字符串更改 int 和 string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62352046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com