Splatterfest233
Splatterfest233

Reputation: 3

python searching for string starting with letter

data = cursor.fetchone ( )
while data is not None:
    data = str(data)
    print(data)
    data.split(",")
    for index in data:
        if index.startswith("K"):
            print(index, end=';')
    data = cursor.fetchone()

Here is the relevant part of my code. The data is retrieved from a mysql server, and is a long string of text separated by commas. I can split the string with the commas fine, however, I then need to search for 4 letter strings. I know they start with K, but when I run the program it only prints the K. How do I get it to print the whole string.
Sample Data:
"N54,W130,KRET,KMPI,COFFEE"
Expected output:
"N54,W130,KRET,KMPI,COFFEE"
"KRET;KMPI;"

Upvotes: 0

Views: 1120

Answers (2)

migjimen
migjimen

Reputation: 571

If you are looking for 4 letters string starting with "K", What about using regular expressions?

import re

regex = r"K[a-zA-Z0-9]{3}"

test_str="N54,W130,KRET,KMPI,COFFEE"

matches = re.finditer(regex,test_str)

output=""
for matchNum, match in enumerate(matches):
    output+=match.group()+";"

print(output)

The output is: KRET;KMPI;

Upvotes: 0

quantik
quantik

Reputation: 816

Your line data.split(",") does nothing because you need to assign that value. You also said you want to only print the K? If so you only want to print the first character of the string so d[0]

data = cursor.fetchone ( )
while data is not None:
    data = str(data)
    print(data)
    data = data.split(",")
    for d in data:
        if d.startswith("K"):
             print(d, end=';')
    data = cursor.fetchone()

EDIT: Based on your edit it seems you want to entire string to be printed so I updated it for that

Upvotes: 2

Related Questions