[英]How can I convert strings to list, without using the split fuction
I am going to convert: sample_date = "23-05-2000" into a list, with while loop.我要将: sample_date = "23-05-2000" 转换为一个列表,带有 while 循环。
example:例子:
"23-05-2000" -> [23, 05, 2000]
import re
s = "23-05-2000"
y = re.sub("-", ", ", s)
z = []
z.append(y)
print(z)
output输出
['23, 05, 2000']
Try the below code using while loop使用 while 循环尝试以下代码
count = 0
a = "23-05-2000"
e = []
c = ""
while(count != len(a)):
if a[count]=="-":
e.append(int(c))
c = ""
else:
c += a[count]
count+=1
e.append(int(c))
#e will have the output you want
You can use the datetime module for this:您可以为此使用datetime模块:
from datetime import datetime
date_string = "23-05-2000"
date_format = "%d-%m-%Y" # zero-padded day, zero-padded month, year with century
dt = datetime.strptime(date_string, date_format)
dt_list = [dt.day, dt.month, dt.year]
print(dt_list)
[23, 5, 2000]
If you have to use a while loop如果必须使用 while 循环
sample_date = "23-05-2000"
part = ''
l = []
while sample_date:
head = sample_date[0]
sample_date = sample_date[1:]
if head == '-':
l.append(int(part))
part = ''
else:
part += head
l.append(int(part))
print(l)
Output输出
[23, 5, 2000]
You could use partition()
to do something with each token of the input:您可以使用
partition()
对输入的每个标记执行某些操作:
input = '23-05-2000'
output = []
while input:
token, _, input = input.partition('-')
do_something_with(token)
output.append(int(token))
# assert(output == [23, 5, 2000])
because we cant use .split() , we had a few approaches.因为我们不能使用.split() ,所以我们有一些方法。
### using a while ###
# Creating variables
input_string = "10-20-30-40-50"
split_character = '-'
run = True
result = []
memory = ''
index = 0
string_size = len(input_string) # here we will discovery the size of the string
### The While cycle
# 1º try - we will run all characters of the string
while run:
# First we'll check if we archive the end do the index
if string_size <= index:
run = False
result.append(int(memory))
break
# Verify if the character on that index is the split_character
# If True : will add on memory the input_string[index]
if input_string[index] != split_character:
memory = memory + input_string[index]
# if the input_string[index] is equals to the split_character, the variable memory will be append to result and reset memory to ''
else:
result.append(int(memory))
memory = ''
index = index + 1
print(result)
You also can use the 'for' to do.你也可以用'for'来做。 Will be much simple also clear.
会简单很多也清楚。 If you had any doubts, just ask.
如果你有任何疑问,就问吧。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.