📌  相关文章
📜  Python – 将分隔符分隔的列表转换为数字

📅  最后修改于: 2022-05-13 01:55:23.998000             🧑  作者: Mango

Python – 将分隔符分隔的列表转换为数字

给定一个带有分隔符分隔数字的字符串,在删除分隔符后连接以形成整数。

方法 #1:使用循环 + split() + int()

这是可以执行此任务的方式之一。在此,我们在分隔符上拆分字符串,然后运行一个循环来连接,最终结果被转换为 int()。

Python3
# Python3 code to demonstrate working of
# Convert Delimiter separated list to Number
# Using loop + split() + join()
 
# initializing string
test_str = "1@6@7@8@5@8@9"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Delimiter
delim = "@"
 
# spliting to get list of string numbers
temp = test_str.split(delim)
res = ''
for ele in temp:
    res = res + ele
 
# converting result into integer
res = int(res)
 
# printing result
print("Constructed integer : " + str(res))


Python3
# Python3 code to demonstrate working of
# Convert Delimiter separated list to Number
# Using join() + split() + int()
 
# initializing string
test_str = "1@6@7@8@5@8@9"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Delimiter
delim = "@"
 
# join used over splitted result
# final result casted using int()
res = int("".join(test_str.split(delim)))
 
# printing result
print("Constructed integer : " + str(res))


输出
The original string is : 1@6@7@8@5@8@9
Constructed integer : 1678589

方法 #2:使用 join() + split() + int()

这是可以执行此任务的另一种方式。在此,我们使用 join() 和 int() 执行最终连接以获得最终结果。

Python3

# Python3 code to demonstrate working of
# Convert Delimiter separated list to Number
# Using join() + split() + int()
 
# initializing string
test_str = "1@6@7@8@5@8@9"
 
# printing original string
print("The original string is : " + str(test_str))
 
# initializing Delimiter
delim = "@"
 
# join used over splitted result
# final result casted using int()
res = int("".join(test_str.split(delim)))
 
# printing result
print("Constructed integer : " + str(res))
输出
The original string is : 1@6@7@8@5@8@9
Constructed integer : 1678589