Understanding strings of Python

Strings in Python are very powerful in terms of the thousand ways they can be handled/ manipulated using the functions and libraries available to handle them.

Python has a built-in class named "str" that handles strings.

Creating strings - 

Strings can be enclosed within a single or double quotes. Double quotes can contain single quotes without any issue and even single quotes can enclose double quotes too. To escape a special character, use backslash \. For example - \n, \' \"

Example of Python strings -  

str_name = "BeingSkilled is an edtech portal" #Here str_name is a variable name that stores the string with text BeingSkilled is an edtech portal

To create strings in multiple lines, use triple quotes """. You can create multiline string by having a backslash on the end of every line to escape the newline character.

Strings in Python are "immutable" meaning strings can't be altered once they are created, therefore, we try creating new strings for manipulating them or computing values using the existing strings. 

Example of Python strings -

str_num1 = 10 ; str_num2 = 20

str_num3 = str_num1 + str_num2 #created a new string that stores the sum of two strings

print(str_num3) 

>> 30    #output 

Understanding Character strings - 

Suppose we have a string, str_sent which has the text string "BeingSkilled". 

str_sent = "BeingSkilled"

In python, index starts from 0.

Therefore, if we want to access the first character of the string str_sent, we will type str_sent[0]. This will print out "B"

print(str_sent[0]) #Prints B

Similarly for str_sent[1], it prints out "e" and so on.

 

To know the length of the string including spaces, use len() function. 

print(str_sent.len()) #Prints 11 

 

How to concatenate two Python strings? 

Use '+' operator to concatenate 

Suppose we have two strings, 

str_sen1 = "Hello"

str_sen2 = "BeingSkilled!"

str_sen3 = str_sen1 + " " + str_sen2  # " "  includes a single space while concatenating two strings

print(str_sen3)

#Output would be Hello BeingSkilled! 

Leave a comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.