Python Text Handling

count

Used to count the number of occurrences of a substring in a given string.

The basic syntax is...

str.count('substring')

where...str is a variable name referencing a stringsubstring is the substring to look for

split

Used to split a string into multiple strings based on a specified delimiter.

The basic syntax is...

str.split(separator, maxsplit)

where...str is a variable name referencing a stringseparator is a string defining the character (or string) on which you wish to split referenced string... e.g. "." or "-"maxsplit controls the number of iterations... e.g a string of 1.2.3.4 with separator set to "." and maxsplit of 1 would return 1 and 2.3.4 (omitting maxsplit would return 1, 2, 3, and 4)

In the example below, rows have been returned from a MySQL Enterprise Monitor database...

#!/usr/bin/python3.6import mysql.connectorimport myloginpath
conf   = myloginpath.parse('mem')
try:        mem    = mysql.connector.connect(**conf,database='mem__inventory',auth_plugin='mysql_native_password')        cursormem = mem.cursor()
        query1 = """SELECT UPPER(e.hostname), m.version, n.port                FROM environment e                JOIN metadata m                JOIN networking n                WHERE e.id=m.id                AND n.id=m.id                """
        cursormem.execute(query1)
        result = cursormem.fetchall()        for row in result:

                host1 = row[0].split(".")

                host = host1[0]

                version,edition = row[1].split("-",1)

                port = row[2]

                print (host,port,version,edition)


except mysql.connector.Error as err:  print("Something went wrong: {}".format(err))
else:        cursormem.close()        mem.close()

The output looks like this...

MYSQLSERVER1 3306 5.6.14 enterprise-commercial-advanced-log

MYSQLSERVER2 3306 8.0.24 commercial

MYSQLSERVER3 3306 8.0.24 commercial

str

Used to convert a non-string variable (perhaps a numeric) to a string.

The basic syntax is...

str(var)

where var can be any variable or expression with a value suitable for conversion to a string.

Bibliography