Python – 将数字字符串拆分为 K 位整数
给定一个字符串,将其转换为 K 位整数
Input : test_str = ‘457336’, K = 2
Output : [45, 73, 36]
Explanation : Divided in 2 digit integers.
Input : test_str = ‘457336’, K = 3
Output : [457, 336]
Explanation : Divided in 3 digit integers.
方法 #1:使用 int() + slice + loop
在此,我们迭代字符串并执行切片直到 K 位,然后使用 int() 执行转换为整数的任务。
Python3
# Python3 code to demonstrate working of
# Split Numeric String into K digit integers
# Using int() + slice + loop
# initializing string
test_str = '457336842'
# printing original string
print("The original string is : " + str(test_str))
# initializing substring
K = 3
res = []
for idx in range(0, len(test_str), K):
# converting to int, after slicing
res.append(int(test_str[idx : idx + K]))
# printing result
print("Converted number list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Split Numeric String into K digit integers
# Using list comprehension + int() + slicing
# initializing string
test_str = '457336842'
# printing original string
print("The original string is : " + str(test_str))
# initializing substring
K = 3
# one liner to solve problem
res = [int(test_str[idx : idx + K]) for idx in range(0, len(test_str), K)]
# printing result
print("Converted number list : " + str(res))
输出
The original string is : 457336842
Converted number list : [457, 336, 842]
方法 #2:使用列表理解 + int() + 切片
与上面类似的方法,只是解决这个问题的简写。
Python3
# Python3 code to demonstrate working of
# Split Numeric String into K digit integers
# Using list comprehension + int() + slicing
# initializing string
test_str = '457336842'
# printing original string
print("The original string is : " + str(test_str))
# initializing substring
K = 3
# one liner to solve problem
res = [int(test_str[idx : idx + K]) for idx in range(0, len(test_str), K)]
# printing result
print("Converted number list : " + str(res))
输出
The original string is : 457336842
Converted number list : [457, 336, 842]