Android Code Snippet PyJoin() - Python 'str.join'

PyJoin() - Returns a string in which the string elements of the given sequence (list / array) have been joined by glue separator.

Usage:

B4X:
Dim strArray() = Array As String("I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "XI", "XII") As String
Dim strList As List : strList.Initialize : strList.Add("A") : strList.Add("B") : strList.Add("C") : strList.Add("D")
Log(PyJoin(", ", strArray))
Log(PyJoin("-", strList))

'Output:
'I, II, III, IV, V, VI, VII, VIII, IX, X, XI, XII
'A-B-C-D

Snippet:

B4X:
Sub PyJoin(glue As String, strList As Object) As String
    Dim lst As List
    Dim out As String
    If GetType(strList) == "[Ljava.lang.String;" Then
        lst.Initialize
        Dim arr() = strList As String
        lst.AddAll(arr)
    Else
        lst = strList
    End If
    For Each str As String In lst
        out = out & str & glue
    Next
    Return out.SubString2(0, out.Length - glue.Length)
End Sub

 
Last edited:

Erel

B4X founder
Staff member
Licensed User
Longtime User
B4X:
Sub PyJoin(Glue As String, Strings As List) As String
   Dim sb As StringBuilder
   sb.Initialize
   For Each s As String In Strings
     sb.Append(s).Append(Glue)
   Next
   If sb.Length > 0 Then sb.Remove(sb.Length - Glue.Length, sb.Length)
   Return sb.ToString
End Sub

Example:
B4X:
Log(PyJoin("-", Array("a", "b", "c", "sdf")))
Log(PyJoin("--", ListOfString)

Advantages:
- Cross platform.
- Much more efficient (if the number of strings is large).
- Doesn't throw an error if the list of strings is empty.
 
Top