Python Forum
How to get first two characters in a string
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to get first two characters in a string
#1
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'
Reply
#2
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
Reply
#3
Ok, that worked. Thank you very much!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  doing string split with 2 or more split characters Skaperen 22 2,317 Aug-13-2023, 01:57 AM
Last Post: Skaperen
  How do I check if the first X characters of a string are numbers? FirstBornAlbratross 6 1,429 Apr-12-2023, 10:39 AM
Last Post: jefsummers
Question [SOLVED] Delete specific characters from string lines EnfantNicolas 4 2,143 Oct-21-2021, 11:28 AM
Last Post: EnfantNicolas
  Extract continuous numeric characters from a string in Python Robotguy 2 2,581 Jan-16-2021, 12:44 AM
Last Post: snippsat
  Python win32api keybd_event: How do I input a string of characters? JaneTan 3 3,726 Oct-19-2020, 04:16 AM
Last Post: deanhystad
  Remove escape characters / Unicode characters from string DreamingInsanity 5 13,420 May-15-2020, 01:37 PM
Last Post: snippsat
  Replacing characters in a string with a list cjms981 1 1,782 Dec-30-2019, 10:50 PM
Last Post: micseydel
  Strange Characters in JSON returned string fioranosnake 4 5,120 Dec-02-2019, 07:25 PM
Last Post: fioranosnake
  Split a long string into other strings with no delimiters/characters krewlaz 4 2,704 Nov-15-2019, 02:48 PM
Last Post: ichabod801
  How to iterate over some characters in a string and the others will stay as it is. ? sodmzs 9 4,324 Jun-17-2019, 06:45 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020