[Python] list conversion and string

        In the process of writing Python, will often need to be between the dictionary, List, String and other types of conversion, this blog is mainly recorded conversion of String and List, in a future post, will meet again in accordance with the white work examples of other types of conversion are recorded.

table of Contents

1.List turn String

1.1 common form of conversion

1.2 Advanced forms of conversion

2.String turn List

2.1 common form of conversion

2.2 Advanced forms of conversion


        Since recently doing NLP related projects, the situation encountered type String and List casts more, where white summarize the various methods used in your own:

1.List turn String

1.1 common form of conversion

List String turn core function is to join, the following is the most common form of conversion 

list1 = ['我','爱','Python']
str1 = "".join(list1)
print (str1)

result:

我爱Python

1.2 Advanced forms of conversion

For this form below, or simply join if the output, then it loses its meaning, see the following situation 

list1 = ['www','baidu','com']
str1 = "".join(list1)
print (str1)

result:

wwwbaiducom

This time, we must understand, join former can add your own symbols, in this scenario, we should do this:

list1 = ['www','baidu','com']
str1 = ".".join(list1)
print (str1)

result:

www.baidu.com

Therefore, when the conversion of the time, we need to think about what kind of results, and then again converted.

2.String turn List

2.1 common form of conversion

String turn List, the easiest is to use the list function, as follows:

str1 = '我爱看电影'
list1 = list(str1)
print (list1)

result:

['我', '爱', '看', '电', '影']

So the situation encountered two characters in one word, this method is not applicable.

2.2 Advanced forms of conversion

Advanced form is to address the following issues, www, baidu, com respectively into words, if it can not achieve the desired effect with a list 

str1 = 'www.baidu.com'
list1 = list(str1)
list2 = str1.split(".")
print ("list1:%s list2:%s"%(list1,list2))

result:

list1:['w', 'w', 'w', '.', 'b', 'a', 'i', 'd', 'u', '.', 'c', 'o', 'm'] list2:['www', 'baidu', 'com']

These are the introduction to the ways of the ~

Published 92 original articles · won praise 125 · views 220 000 +

Guess you like

Origin blog.csdn.net/Jarry_cm/article/details/104914405