简体   繁体   English

字符串到列表和列表到字符串的转换 - 没有拆分

[英]string to list and list to string conversion - without split

Could you share how to convert string to list and vice versa as shown below (without splitting each words)您能否分享如何将字符串转换为列表,反之亦然,如下所示(不拆分每个单词)

  • Input: string 'I am a boy'输入:字符串'I am a boy'
  • Output: ['I am a boy'] Output: ['I am a boy']

and

  • Input: list ['I am a boy']输入:list ['I am a boy']
  • Output: string 'I am a boy' Output:字符串'I am a boy'

Just to be clear, The first part is pretty straightforward and did implemented before the post.需要明确的是,第一部分非常简单,并且在发布之前已经实现。 I just stuck for the 2nd problem.我只是坚持第二个问题。

To "convert" a string to a list, you can just place it in one, eg, by creating a new list with [] :要将字符串“转换”为列表,您可以将其放在一个列表中,例如,通过使用[]创建一个新列表:

input1 = 'I am a boy'
output1 = [input1]

To "convert" a list like you have to a string, you could simply extract the first and only value in it:要将列表“转换”为字符串,您可以简单地提取其中的第一个也是唯一的值:

input2 = ['I am a boy']
output2 = input2[0]

String to list (supposing it's a list with just 1 string, as per your image)要列出的字符串(假设它是一个只有 1 个字符串的列表,根据您的图像)

inp = 'I am a boy'
lst = [input]

List to string (supposing it's a list with just 1 element of type string)列表到字符串(假设它是一个只有 1 个字符串类型元素的列表)

inp = ['I am a boy']
string = input[0]

If you want to force casting (maybe cause you have a list of integers), you can use the str() function, such as str(inp[0]) where inp[0] is maybe a number如果你想强制转换(可能是因为你有一个整数列表),你可以使用str() function,例如str(inp[0])其中inp[0]可能是一个数字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM