[英]How to merge consecutive letters and consecutive numbers from a string to a list separetely?
Say I have the following string:假设我有以下字符串:
string1 = 'Twenty 20 Twelve 12'
I would like to convert it into a list that would keep words as strings in separate elements, and numbers in another (as integers):我想将它转换成一个列表,将单词作为字符串保存在单独的元素中,并将数字保存在另一个元素中(作为整数):
list1 = ['Twenty', 20, 'Twelve', 12]
My current code looks is:我当前的代码看起来是:
list1 = [y for y in string1.replace(' ','')]
and the result prints out as:结果打印为:
['T','w','e','n','t','y','2','0','T','w','e','l','v','e','1','2']
How would I be able to write a code to keep words in separate entries, and turn numbers inside the string into integers in the list?我如何才能编写代码以将单词保存在单独的条目中,并将字符串中的数字转换为列表中的整数? I am a beginner to programming who is currently learning Python in parallel with C.
我是编程初学者,目前正在与 C 并行学习 Python。
Look into the .split()
function.查看
.split()
函数。
It takes the form of它采用以下形式
str.split(sep=None, maxsplit=-1)
so you want your code to look like this to break it apart.所以你希望你的代码看起来像这样来分解它。
string1 = 'Twenty 20 Twelve 12'
string1.split()
#['Twenty', '20', 'Twelve', '12']
To convert the numbers to integers, just check for .isdigit()
要将数字转换为整数,只需检查
.isdigit()
[int(i) if i.isdigit() else i for i in string1.split()]
#['Twenty', 20, 'Twelve', 12]
if you're not familiar with list comprehensions , this is analogous to如果您不熟悉列表推导式,这类似于
values = []
for i in string1.split():
if i.isdigit():
values.append(int(i))
else:
values.append(i)
values
#['Twenty', 20, 'Twelve', 12]
You really should google it....你真的应该谷歌一下......
but you can use split
但你可以使用
split
string1 = 'Twenty 20 Twelve 12'
list1=string1.split(' ')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.