Python – Exploring strings

Hello friends,

Today in this article we are going to discuss about strings in Python

What is string in Python?

A string is a sequence of characters.

A character is simply a symbol. For example, the English language has 26 characters (A-Z).

How to create a string in Python?

Strings can be created by enclosing characters inside a single quote or double-quotes. Even triple quotes can be used in Python but generally used to represent multiline strings.

Defining a string

# Defining a string using single quote
string1 = 'Hello world'
print(string1)

# Defining a string using double quotes
string2 = "Hello world"
print(string2)

# Triple quotes string can extend multiple lines
string3 = '''Welcome to 
Knowledge junction'''
print(string3)
-------------------------------------------------
In[1] runfile (...)
Hello world
Hello world
Welcome to 
Knowledge junction

How to print a sting using print() function

print("Hello world")
---------------------------------------------------
In[1] runfile (...)
Hello world

How to access characters in a string?

fig – 1 Knowledge junction text

#Accessing string characters in Python

str = 'Knowledge junction'
print('str = ', str)

#first character
print('str[0] = ', str[0])

#last character
print('str[-1] = ', str[-1])
--------------------------------------------
In[1] runfile (...)
str =  Knowledge junction
str[0] =  K
str[-1] =  n

Concatenation of Two or More Strings

# Python String Operations
str1 = 'Hello'
str2 ='World'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)
------------------------------------------
In[1] runfile (...)
str1 + str2 =  HelloWorld
str1 * 3 = HelloHelloHello

Iterating through a string

We can iterate through a string using a for loop.

# Iterating through a string
count = 0
for letter in 'Hello World':
    if(letter == 'l'):
        count += 1
print(count,'letters found')
-----------------------------------
In[1] runfile (...)
3 letters found

String Membership Test

'a' in 'program'
------------------
True

'a' not in 'battle'
------------------
False

We have very good series of Python articles, please have a look –

Thank you

Have a nice day 🙂

You may also like...

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: