In this tutorial we are going to learn :

  • Strings in Python
  • Length of Strings
  • Accessing Characters in Python
  • Escape Sequences
  • Formatted Strings
  • String Methods

 

 

Strings in Python

 

String is a basically sequence of characters. We create them by enclosing characters in quotes. We can also use a triple quotation mark.

Example : 

my_name = "James"
message = """
Hi 
Python is a great language to learn.

"""

print(my_name)
print(message) 

 

Length of Strings

 

We use the len() function to get the length of the strings.

Example : 

message = Python Programming"

print(len(message)) 

 

Accessing Characters in Python

 

We use [ ]  to get string characters in Python.

Example : 

message = "Python Programming"

print(message[0])
print(message[-1])
print(message[0:4])
print(message[0:])
print(message[:5])
print(message[:]) 

 

Escape Sequences

 

We cannot add some specific characters in String quotes. But if it is necessary we use escape character ( \ ) to do that. The escape character skips the next first character from itself.

  • Look at the example program below. We just put ” character in string quotes
    and Python will give an error for that.

Example :

  • We use escape character ( \ ) to fix that. Look at the program below.
message = "Python \Programming "

print(message) 
  • Important Note Here :

There are some rules in Python such as : 

  • \ n : newline
  • \ t : a tab
message = "Python \nProgramming "
message1 = "1 \t2 \t3 \t4 \t5"

print(message)
print(message1) 
  • Look at another example below

Two ways to fix that. We can use escape character or Raw String.

print("C:\\Users\\tomy\\notes.txt")
print(r"C:\Users\tomy\notes.txt") 

 

Formatted Strings

 

Earlier we learned how to combine two strings or integer and string together. We have a better way and a more professional way to combine any data types.
We use a formatted string for it.

Look at the Example Program Below.

Example :

You see that we get an error.

We can fix it by using a formatted string. Look at the example below.

first_name = "James"
my_age = 25

print(f"{first_name} is {my_age} years old. ") 


String Methods


In Python, we have some string methods to do some task on strings. Look at the
example

Example : 

message = " Python Programming"

print(message.upper())
print(message.lower())
print(message.find("thon"))
 

 

 

  • If you want to learn more about Python string methods then click here. 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments