Python – Understanding how strings work with examples

In this tutorial I will let you know how to use strings in Python. In Python we can declare a string in either double quotes or single quotes. Both are same. Like the following way.

s1 = "This is string s1"
s2 = 'This is string s2' 

So here in above example both s1 and s2 are strings and work the same way.

Also strings are like arrays i.e each character can be accessed using its index. Like s[0], s[1]… just like how lists work. The following are valid operations.

print("s3[0]= ", s3[0])
print("s3[0:10]= ", s3[0:10])

Now if we know to access index we also might need to know the length of the string. So len() is a predefined function that gives us the length. Following are valid operations.

s1_len = len(s1)
s2_len = len(s2)
print("s1-len = %s, s2-len = %s, s3-len = %s"%(s1_len, s2_len))

To concatenate two strings we use + operator just like adding two numbers.

s3 = s1 + ' ' + s2 #this is string concatenation

Bonus:

Convert string to integer. Now we might arrive at a case where a string variable has number in it, but you want to convert it into number to do numeral operations. So the following code will do the same.

#convert a string into integer
print("string to int conversion")

s5 = '10' # is a string, not a number
print("s5-type=", type(s5), "value=", s5)  #here you cannot do numerical operations like addition/substraction etc on s5 variable because it is a string

num = int(s5)
print("num-type=", type(num), "value=", num) #now you can do numerical operations like addition/substraction etc on num variable

Overall code for strings that you can just copy, run and play with.

# in python a string can be given in as many ways as following

s1 = "This is string s1"
s2 = 'This is string s2' 
s3 = ""
s4 = s1 + ' ' + s2 #this is string concatenation

print(s1,s2, s3, s4, sep='\n')
#Notice the sep='\n', it will seperated each variable with new line(it can be '\t' also, by default its space)

print("to print length of string")

s1_len = len(s1)
s2_len = len(s2)
s3_len = len(s3)
s4_len = len(s4)

print("s1-len = %s, s2-len = %s, s3-len = %s, s4-len = %s"%(s1_len, s2_len, s3_len, s4_len))

#string are sequence of characters like arrays(but not array), but each
#character in the string can be accessed like array using indices

print("s4[0]= ", s4[0])
print("s4[0:10]= ", s4[0:10])


#convert a string into integer
print("string to int conversion")

s5 = '10' # is a string, not a number
print("s5-type=", type(s5), "value=", s5)  #here you cannot do numerical operations like addition/substraction etc on s5 variable because it is a string

num = int(s5)
print("num-type=", type(num), "value=", num) #now you can do numerical operations like addition/substraction etc on num variable

Leave a Reply

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