Python Strings

Anything inside a single(‘) or double(“) quotes in Python is considered to be a string generally i.e if you put anything inside single or double quotes then it will be considered as a Python Strings e.g. “string”, ‘string’, “I Am A String”, etc.

Printing a String

We use the “print()” statement to print a string in the terminal.

Example

print("Hello,I am a string")
print('Hello,I am also a string')

Output

Hello,I am a string
Hello,I am also a string

Assigning String to Variable

Example

a = "Hello"  
b = """This is 
a multiline
string"""
c = '''This is
also a multiline
string'''
print(a)
print(b)
print(c)

Output

Hello
This is
a multiline
string
This is
also a multiline
string

Indexing in Strings

Python provides both types of indexing i.e. positive and negative.

Positive indexing starts from the left end with “0” and negative indexing starts from the right end with “-1“.

String Slicing

String slicing means choosing or returning some characters from the string. In python, anything inside single or double quotes is considered to be a string and the spaces are also counted during the indexing of a string.

Example

mystr = "I am a string"
print(len(mystr))  # 13
print(mystr[0])  # 'I'
print(mystr[1])  # ' '  blank space
print(mystr[0:len(mystr)])  # full string
print(mystr[:])  # here python automatically assigns 0 and
                 # value of length of string
print(mystr[-2:-1])  # 'n'
print(mystr[-14:-1])  # full string excluding 'g'
print(mystr[:100])  # full string (no errors)

Output

13
I
 
I am a string
I am a string
n
I am a strin
I am a string

Note: Here the second value after “:” is subtracted by “1”.

String Concatenation

String concatenation means to add two strings. We use the “+” operator to concatenate strings.

Example-1

x = "Hello "
y = "World"
z = x + y
print(x + y)
print("Hello " + "World")
print(z)

Output

Hello World
Hello World
Hello World

Let’s see one more example–

Example-2

x = "2"
y = "4"
print("12.3" + "34.6")  # string concatenation
print(x + y)  # string concatenation
print(int(x) + int(y))  # simple addition

Output

12.334.6
24
6

Comma in print() statement

We use comma(,) inside the print() statement with many objects or data types like strings, functions, lists, sets, etc.

But its working is something like it creates a space between two objects inside print() statement whether it is a string or list or any other object or datatype.

We can use commas to separate strings and numbers in print() statements.

Example

print("This name is", "Harry")
print("My roll number is", 21)

Output

This name is Harry
My roll number is 21

“end” inside print() statement

We use the “end” inside the print() statement to insert some characters including space at the end of the string and also we can restrict the print() statement to not change the line which the print() statement does by default.

Example

print("Hello")
print("World")
print("Hello", end="")  # no line change will happen
print("World")
print("Hello", end=" ")  # no line change only space will be inserted
print("World")
print("Hello", end=" my ")  # inserting my between Hello and World
print("World")

Output

Hello
World
HelloWorld
Hello World
Hello my World

format() method

We can use the format() method after strings which are used to insert specified values inside strings.

We use “{}” to insert specified values.

There are three ways to insert values.

1. {valuename}

2. {valueindex}

3. {}

Example

print("Name:{name} and age:{age}".format(name="Harry", age=30))
print("Name:{0} and age:{1}".format("Harry", 30))
print("Name:{1} and age:{0}".format("Harry", 30))
print("Name:{} and age:{}".format("Harry", 30))

Output

Name:Harry and age:30
Name:Harry and age:30
Name:30 and age:Harry
Name:Harry and age:30

Fast String

Denoted with “f“, the fast string also works the same as the format() method, but this makes work easier and faster. See the example below-

Example

name = "Harry"
age = 30
print(f"Name:{name} and age:{age}")
print(f"Addition:{5+4}")
print(f"Multiplication:{eval('1+2//4-20*9')}")
''' eval() is a built-in function
    used to calculate a string 
    which contains some arithematic
    calculations of numbers'''

Output

Name:Harry and age:30
Addition:9
Multiplication:-179

String Length

We use “len()” to know the length of any string.

Example

a = "Hello"  
b = """This is 
a multiline
string"""
c = '''This is
also a multiline
string'''
print(len(a))
print(len(b))
print(len(c))

Output

5
27
31

lower() method

If we type “stringname.lower()” then this method will return the string having all letters in lowercase.

Example

mystring = "I Am A String"
print(mystring.lower())

Output

i am a string

upper() method

If we type “stringname.upper()” then this method will return the string with all letters to uppercase.

Example

mystring = "I Am A String"
print(mystring.upper())

Output

I AM A STRING

replace() method

This method is used to replace a string or letters with another string.

Example

mystring = "I Am A String"
print(mystring.replace("I", "This"))

Output

This Am A String

Escape Characters

If we want to output– I am “A” string using the code– print(“I am “A” string”), then python will give you a syntax error.

Example

print("I am "A" string")

Output

File "f:/vscode/python/escape.py", line 1
    print("I am "A" string")
                 ^
SyntaxError: invalid syntax

If we use backslash “\” followed by the character like ” then the problem will get resolved.

Hence, an escape character is a backslash followed by a character you want.

Example

print("I am \"a\" String")
print("Printing in \nNew Line")
print("Printing with a \ttab space")
print("Printing a single quote\'")

Output

I am "a" String
Printing in
New Line
Printing with a         tab space
Printing a single quote'

Important Escape Characters

Escape CharacterName
\’Single Quote
\\Backslash
\nNew Line
\tTab
\bBackspace
\”Double Quote
Escape Characters Table

Also Read:


Auto Login with Python

So today we will learn how to auto login in a tab using Python. So, let’s first see the code, and then we will understand the code through comments. Code # importing the tkinter module from tkinter import * # defining a function def fun(): # defining autologin function and upon calling this function #…

Continue Reading Auto Login with Python

Adding three matrices

In python, it’s very easy to deal with matrices due to its simple syntax and we create matrices using nested lists in python. We simply create matrices by creating lists inside lists as follows matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] As you can see we created lists inside a list…

Continue Reading Adding three matrices

GUI Age Calculator

Hello friends, today we will make an age calculator using python’s GUI library tkinter so, let’s start. Python offers a very good GUI library i.e. tkinter which is very easy to learn and use. Here, we are creating a GUI application to calculate age using a button. We will ask the user to enter the…

Continue Reading GUI Age Calculator

Displaying Images in tkinter

Hello guys, as usual we are sharing one more source code using which you can display images inside your GUI screen of tkinter We will restrict ourselves to .png format only. For .jpg format, we have given an example as comments Tkinter GUI is a python library which is designed in such a way that…

Continue Reading Displaying Images in tkinter

2 thoughts on “Python Strings

Comments are closed.