程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python pure number list converted to string problem

編輯:Python

The join() function in Python is used to combine all elements in a sequence into a new string according to the specified delimiter.
Commonly used to convert list, tuple, dictionary type data into strings
Use syntax: 'sep'.join(seq)
Parameter description:
sep: specify the separator, can be empty.
seq: The sequence of elements to be connected, which can be a list, a tuple, or a dictionary.
Return value: a new string composed of the specified delimiters

Convert list to string (python3)
Example 1: List elements are all string data types

# Convert a list whose elements are all string data types to stringsa = ['1', '2', '3', 'abc', 'def']print('results:', ''.join(a))

Result: 123abcdef

Example 2: Number type data exists in the list element


Problem: When there is numeric type data in the list element,Error!
Reason: When using the join() function to combine list type data, all the elements in the list need to be of string type.
The solution to the above error: ensure that all the elements in the list are converted into strings
Therefore, the above error code can be changed to:

# There is numeric type data in the list element, the correct spellingb = [1, 2, 3]b = [str(i) for i in b]b1 = [1, 2, 3, 'a']b1 = [str(i) for i in b1]print('bresults:', ''.join(b))print('b1 result:', ''.join(b1))

b result: 123
b1 result: 123a

—end—


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved