Come convertire una lista in stringa in Python

Convertire una str
List in stringa in Python
Potremmo usare il metodo str.join()
per convertire una lista che ha elementi di tipo str
data type in una stringa.
Per esempio,
A = ["a", "b", "c"]
StrA = "".join(A)
print(StrA)
## StrA is "abc"
Il metodo join
concatena un numero qualsiasi di stringhe, la stringa il cui metodo è chiamato viene inserita tra ogni stringa data. Come mostrato nell’esempio, la stringa ""
, una stringa vuota, viene inserita tra gli elementi della lista.
Se si vuole che venga aggiunto uno spazio " "
tra gli elementi, allora si dovrebbe usare
StrA = " ".join(A)
## StrA is "a b c"
Convertire una non-str
lista in una stringa in Python
Il metodo join
richiede il tipo di dati str
come parametri dati. Pertanto, se si tenta di entrare nella lista dei tipi int
, si otterrà il TypeError
.
>>> a = [1,2,3]
>>> "".join(a)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
"".join(a)
TypeError: sequence item 0: expected str instance, int found
Il tipo int
dovrebbe essere convertito in str
type prima di essere unito.
comprensione della lista
>>> a = [1,2,3]
>>> "".join([str(_) for _ in a])
"123"
funzione map
>>> a = [1,2,3]
>>> "".join(map(str, a))
'123'
La funzione map
applica la funzione str
a tutti gli elementi della lista a
, e restituisce un oggetto map
iterabile.
"".join()
itera tutti gli elementi dell’oggetto map
e restituisce gli elementi concatenati come stringa.
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn FacebookArticolo correlato - Python String
- Come controllare una stringa è vuota in modo pitonico
- Converti una stringa in nome variabile in Python
- Come rimuovere gli spazi bianchi in una stringa in Python
- Estrai numeri da una stringa in Python
- Come convertire una stringa in datario in Python
- Come convertire una stringa in minuscola in Python 2 e 3