Python String

Python string is a collection of characters. It is an immutable collection. 

This lesson covers the following topics.

What is a string?

_ Python string is an ordered collection of characters. 

_ String is an immutable object.

_ A string can be created using quotes (single quotes or double quotes)

x = "abc"
y = "123"
d = "भारत"
e = 'This is a String'
e = str(123)
f = str([1,3,4])


Getting a character or substring

Accessing Characters - You can access individual characters in a string using indexing.  

Example

my_string = "Hello, World!"
print(my_string[0])   # Output: 'H'
print(my_string[-1])  # Output: '!'

Outcome

H
!

_String Slicing You can extract a substring from a string using slicing. Slicing allows you to specify a range of indices to extract a portion of the string. The syntax for slicing is string[start:end:step].

Example

my_string = "Hello, World!"
print(my_string[0:5])    # Output: 'Hello'
print(my_string[7:])     # Output: 'World!'
print(my_string[::2])    # Output: 'Hlo ol!'

Outcome

Hello
World!
Hlo ol!

Membership test in a string
  • To test whether a string or character is a member of another string in Python, you can use the in or not in operators. 
  • These operators return True or False

Eaxmple

b = "Python"
print("P" in b)

Outcome

True

Example

b = "Python"
print("th" in b)

Outcome

True

Example

b = "Python"
print("yy" in b)

Outcome

False


Concatenation in a string

You can concatenate (join) two or more strings using the + operator. It creates a new string by combining the characters from multiple strings.

Example

string1 = "Hello"
string2 = "World"
result = string1 + ", " + string2
print(result)    # Output: 'Hello, World'

Outcome

Hello, World

Iteration in a string

In Python, a for loop can be used to iterate over the characters in a string.

Example

string1 = "Hello"
for character in string1:
    print(character)

Outcome

H
e
l
l
o


String Formatting

String formatting allows you to create dynamic strings by embedding variables or expressions within a string. Python provides several approaches for string formatting, including the format() method, and f-strings.

Example

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
# Output: 'My name is Alice and I am 25 years old.'

Outcome

My name is Alice and I am 25 years old.


Common String Methods

Python provides a variety of built-in methods that you can apply to strings. Here's an example using a few of these methods:

upper(): Returns a copy of the string in uppercase.

string = "hello"
print(string.upper())

Outcome

HELLO

lower(): Returns a copy of the string in lowercase

string = "CODING CHASKA"
print(string.lower())

Outcome

coding chaska

strip(): Returns a copy of the string with leading and trailing whitespace removed.

string = "   hello   "
print(string.strip())

Outcome

hello

replace(): Returns a copy of the string with all occurrences of a substring replaced with another substring

s = "hello world"
s2= s.replace("world","India"))
print(s2)

Outcome

hello India

split(): Returns a list of substrings separated by a specified delimiter

string = "hello,world"
l = string.split(","))
print(l)

Outcome

["hello", "world"]

count(): Returns the number of occurrences of a specified substring in the string

string = "hello world"
print(string.count("l"))

Outcome

3

isalpha(): Returns True if all the characters in the string are alphabetic, otherwise returns False.

string = "hello world"
print(string.isalpha())

Outcome

False

isdigit(): Returns True if all the characters in the string are digits, otherwise returns False.

string = "12345"
print(string.isdigit())

Outcome

True


We have many more methods available for a python string. Visit here - https://www.programiz.com/python-programming/methods/string