Python

Python Strings

Strings are used in python for recording text information such as address. Python Strings are basically a sequence, i.e. python keeps track of each and every element of the string as a sequence. 

For example python understands the word ‘Hello World’ as a sequence of letter in a specific order. This also enables us to slice or index the string.

String Creation

To create a string in python you need to use either single quotes, double quotes or triple double quotes. Let’s see this in the example.

# A string can contain one word or an entire sentence in it
>>>'hi'
'hi'
>>>'hello world'
'hello world'
# we can also put string in double quotes
>>>"I'm also a string"
"I'm also a string"
>>> """Yes I'm also a string"""
"Yes I'm also a string"

But you have to be careful with quotes. For example, you need to write didn’t and you put this string in single quotes it will throw an error. I will recommend you to open the IDLE and see for this yourself now.

In case you are new to python and don’t know what IDLE is, you can visit this tutorial

>>> 'didn't'
SyntaxError: invalid syntax

To correct this by two methods:

>>> 'didn\'t'
"didn't"
>>> "didn't"
"didn't"

Printing Strings

To print a string you need to call the print function and pass the string as an argument. Alternatively, you can also pass a variavle which contains the string.

>>> print("Hello World")
Hello World
>>> a = "Hello"
>>> print(a)
Hello

String Basic Operations

Concatenating two strings

>>> a = "Hello " + "World"
>>> print(a)
Hello World

A String once created is immutable i.e. it’s sub parts cannot be changed.

Let’s see this in an example.

Related Post
>>> a[0]
'H'
>>> a[0] = 'e'
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    a[0] = 'e'
TypeError: 'str' object does not support item assignment

Here we tried to change the string’s first character but we failed because strings are immutable.

Finding Length of the String

We can use inbuilt len() function. This function returns the length of a iterable.

>>> len(a)
11

String Indexing and Slicing

Since strings in python are sequence, python can use indexes to call parts of it.

To index a sequence we use [], square brackets with an integer filled inside it. In python, indexing starts from 0. Let’s see some examples to make you understand better.

Indexing

>>> a[0]
'H'
>>> a[5]
' '
>>> a[-1]
'd'
>>> a
'Hello World'

Indexing starts from 0 from the start of the string and from -1 from the last character of the string.

Slicing

You can slice strings by placing [start_index:index_of_desired_character + 1] after an object

>>> a[:] #Call Everything
'Hello World'
>>> a[1:] #Call from 1 to last character
'ello World'
>>> a[:-1] #Call from 0 to second last character
'Hello Worl'
>>> a[:10]
'Hello Worl'
>>> a[::2] #grab everything in steps of 2
'HloWrd'
>>> a[::] #grab everything
'Hello World'

String Methods

There are many inbuilt methods for a string object. Some of them don’t require an argument to be passed where as some do. To use a string method we use this format -> object.method(args)

Some in built methods

>>> a.upper() #coverts a string to uppercase
'HELLO WORLD'
>>> a.lower() #converts a string to lowercase
'hello world'
>>> a.split(' ') #splits a string by ' ' space.
['Hello', 'World']
>>> a.split('o') #splits a string a given character
['Hell', ' W', 'rld']

Print Formatting

We can use format() method to insert a formatted objects to printed string.

>>> "Hello {}".format("World")
'Hello World'

Aditya Kumar

Share
Tags: Python Python Basic Tutorial

Recent Posts

  • Programming

Mastering Print Formatting in Python: A Comprehensive Guide

In Python, the print() function is a fundamental tool for displaying output. While printing simple…

8 months ago
  • Programming

Global Variables in Python: Understanding Usage and Best Practices

Python is a versatile programming language known for its simplicity and flexibility. When working on…

8 months ago
  • Programming

Secure Your Documents: Encrypting PDF Files Using Python

PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…

8 months ago
  • Programming

Creating and Modifying PDF Files in Python: A Comprehensive Guide with Code Examples

PDF (Portable Document Format) files are widely used for document exchange due to their consistent…

8 months ago
  • Programming

Boosting Python Performance with Cython: Optimizing Prime Number Detection

Python is a high-level programming language known for its simplicity and ease of use. However,…

8 months ago
  • Programming

Using OOP, Iterator, Generator, and Closure in Python to implement common design patterns

Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…

8 months ago

This website uses cookies.