Python Forum
How to get first two characters in a string - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/Forum-Python-Coding)
+--- Forum: General Coding Help (https://python-forum.io/Forum-General-Coding-Help)
+--- Thread: How to get first two characters in a string (/Thread-How-to-get-first-two-characters-in-a-string)



How to get first two characters in a string - scratchmyhead - May-19-2020

I have a tuple that I converted the first part of the tuple into a string and I want to get the first two characters of that variable. For example

def searchfinmonth():
    conn = sqlite3.connect('financial.db')
    c = conn.cursor()
    c.execute("SELECT * FROM totals")
    records = c.fetchall()

    lb.delete(0, END)

    for record in records:
        a = record[0:1]   #this is equal to '05-18-2020'
        b = a[0:2]   #this should be equal to '05' but instead is equal to '05-18-2020'

        lb.insert(END, str(record[0:1]) + "   "+str(fincombo.get()[0:2]))
        lb.insert(END, b)
        if record[0:1] == fincombo.get()[2]:
            lb.insert(END, fincombo.get())
Where the variable a is equal to "05-18-2020" and I'm trying to get the first two characters of variable a which would be '05' but instead it gets the whole variable which is '05-18-2020'


RE: How to get first two characters in a string - deanhystad - May-19-2020

You are getting lists when you want to get elements.
a = ['one', 'two', 'three']
b = a[0:1] # Gets a list
c = b[0:2] # Gets a list
x = a[0]   # Gets a string from the list
y = x[:2]  # Gets a substring from the string
print(b, c, x, y)
Output:
['one'] ['one'] one on



RE: How to get first two characters in a string - scratchmyhead - May-19-2020

Ok, that worked. Thank you very much!