Getting Started

Python - IntroductionPython - Hello World ProgramPython - SyntaxPython - Data TypesPython - Variables

Operators

Python - Arithmetic OperatorsPython - Relational OperatorsPython - Logical OperatorsPython - Assignment OperatorsPython - Bitwise OperatorsPython - Membership OperatorsPython - Identity OperatorsPython - Increment and Decrement Operators

Conditions

Python - If Else statement

Loop

Python - While LoopPython - For Loop

Numbers

Python - NumbersPython - Number Conversion

Strings

Python - StringsPython - String OperatorsPython - String FormattingPython - String MethodsPython - String Format Method

List

Python - ListPython - List Methods

Tuple

Python - Tuple

Set

Python - SetPython - Set Methods

Dictionary

Python - DictionaryPython - Dictionary Methods

Functions

Python - FunctionsPython - Functions - Variable length argumentsPython - Lambda Function

Scope of Variables

Python - Scope of Variables

Modules

Python - ModulesPython - Math ModulePython - JSON ModulePython - datetime ModulePython - time Module

I/O

Python - Read input from keyboard

File

Python - File Handling

Exception Handling

Python - Exception Handling

OOP

Python - Classes and ObjectsPython - Class Constructor __init__ methodPython - Class Destructor __del__ methodPython - Built-in Class AttributesPython - InheritancePython - Method OverridingPython - Method Overloading

Package Management

Python - PIP

Python - MySQL

Python - MySQL - Getting StartedPython - MySQL - Insert dataPython - MySQL - Select dataPython - MySQL - Update dataPython - MySQL - Delete data

Python - CSV

Python - Read data from CSV filePython - Write data in CSV file

Python - Strings

Python

python logo

In this tutorial we will learn about String in Python.

What is a string?

A string is a sequence of characters enclosed in single ' or double " quotes.

In the following Python program we are creating a string using single and double quotes.

# string
str1 = 'Hello World'
str2 = "Hello World"

print(str1, type(str1))
print(str2, type(str2))

The above program will give the following output.

Hello World <class 'str'>
Hello World <class 'str'>

We can create multiline string using triple quotes '''.

In the following Python program we are creating multiline string.

# variable
str = '''Hello World
This is a multi line
string.
'''

print("str type:", type(str))
print(str)

The above program will print the following output.

str type: <class 'str'>
Hello World
This is a multi line
comment

Accessing string characters

Characters of a string can be accessed using position index.

Lets say, we have a string "Jane Doe".

We can present given string like the following.

+--------+---+---+---+---+---+---+---+---+
| index  | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
+--------+---+---+---+---+---+---+---+---+
| string | J | a | n | e |   | D | o | e |
+--------+---+---+---+---+---+---+---+---+

The string "Jane Doe" consists of 8 characters (space included).

We can see that the first character gets the index 0, the second character gets the index 1 and so on.

If we want to access the first character of the string then we can use the index 0.

In the following Python program we are printing the first, third and the sixth character of the string "Jane Doe".

# variable
str ="Jane Doe"

print("first character: index 0:", str[0])
print("third character: index 2:", str[2])
print("sixth character: index 5:", str[5])

We will get the following output.

first character: index 0: J
third character: index 2: n
sixth character: index 5: D

Substring

We can extract a substring from a given string by mentioning the start and end index within square brackets.

str[start:end]

Where start is the starting index from were we begin the extraction.

And end denotes the ending index. We extract till the end index but not include it.

In the following Python program we have a string "Jane Doe" and we are extracting a substring from the start index 1 till end index 6 (but not including end index).

# variable
str  = "Jane Doe"

substr = str[1:6]

print(substr)          # "ane D"

The len function

We use the len() function to find the length (total number of characters) of a given string.

# variable
str = "Jane Doe"

# find length
l = len(str)

# output
print("length:", l)

We will get the following output.

length: 8

The lower function

We use the lower function to convert a given string to lower case.

In the following example we are converting a given string into lower case.

# variable
str = "Jane Doe"

print("before:", str)

str_lower = str.lower()

print("lowercase:", str_lower)

print("after:", str)

We get the following output.

before: Jane Doe
lowercase: jane doe
after: Jane Doe

The lower() function returns a new string without changing the original string.

The upper function

We use the upper function to convert a given string to upper case.

In the following example we are converting a given string into upper case.

# variable
str = "Hello World"

print(str.upper())        # HELLO WORLD

The strip function

We use the strip function to strip white spaces from the start and end of a given string.

In the following example we are stripping white spaces from the string.

# variable
str = " Hello World  "

str_len = len(str)

stripped_str = str.strip()

stripped_str_len = len(stripped_str)

print("original:", str, "len:", str_len)
print("stripped:", stripped_str, stripped_str_len)

We will get the following output.

original:  Hello World   len: 14
stripped: Hello World len: 11

The split function

We use the split function to split a given string using some delimiter and we get back a list.

In the following Python program we are splitting the string "The quick brown fox jumps over the lazy dog" using space.

# variable
str = "The quick brown fox jumps over the lazy dog"

words = str.split(" ")

print(words)

We will get the following output.

['The', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']

The replace function

We use the replace function to replace a given string with another string.

In the following Python program we are replacing all o letters with 0.

# variable
str = "Hello World"

# replace
modified_str = str.replace('o', '0')

# output
print("original:", str)
print("modified:", modified_str)

We will get the following output.

original: Hello World
modified: Hell0 W0rld

In the following example we are replacing a string lo with LO.

# variable
str = 'hello world'

# replace
modified_str = str.replace('lo', 'LO')

# output
print("original:", str)
print("modified:", modified_str)

We will get the following output.

original: hello world
modified: helLO world

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT