Substring

result = my_string[first_index:last_index_plus_one]

result = my_string[3:6]    //Get the characters from index 3 up to index 5 (the last index given is not included)

result = my_string[:6]    //Get all the characters up to index 5 (the last index given is not included)

result = my_string[3:]    //Get the characters from index 3 up to the end of the string

result = my_string[-2:]    //Get the last 2 characters of the string

result = my_string[:-2]    //Get the string excluding the last 2 characters

Convert string to value

#string to int
#my_variable = int(my_string)
my_variable = int(float(my_string))    #This is better as int('0.0') will throw an error in python ('0.0 is not a valid integer of base 10')

#string to float
my_variable = float(my_string)

Get string from character position # (Remove text from beginning or end of string)

Getting beginning of a string
    if my_string.find("abc") >= 0:
        my_string = my_string[:my_string.index("abc")]
Getting end of string
    if my_string.find("abc") >= 0:
        my_string = my_string[my_string.index("abc")+3:]

Feel free to comment if you can add help to this page or point out issues and solutions you have found. I do not provide support on this site, if you need help with a problem head over to stack overflow.

Comments

Your email address will not be published. Required fields are marked *