Python Tutorials

Python Programs

Python Strings


Python Strings

In this tutorial, we will learn about strings in Python. We will cover the basics of string manipulation, including creating, accessing, modifying, and performing operations on strings.


What is a String

A string in Python is a sequence of characters. Strings in Python can be created using single quotes, double quotes, or triple quotes. Strings are used for storing and handling text data.


Creating Strings

Strings can be created in Python using single or double quotes:

str = "Hello, world!"

Strings can also be created using triple quotes for multi-line strings:

str2 = '''Hello,
world!'''


Initializing Strings

  1. Create a string variable and initialize it with a value.
  2. Print the string variable using print.

Python Program

str = "Hello, world!"
print(str)

Output

Hello, world!


Accessing Characters in a String

  1. Create a string variable and initialize it with a value.
  2. Access and print individual characters using array indexing.

Python Program

str = "Hello"
print(str[0]) # Accessing using array indexing
print(str[1])

Output

H
e


Modifying Strings

  1. Create a string variable and initialize it with a value.
  2. Strings in Python are immutable, so you cannot modify individual characters directly. However, you can create new strings based on modifications.
  3. Print the modified string.

Python Program

str = "Hello"
new_str = 'J' + str[1:] # Creating a new string with modification
new_str += " World!" # Appending new characters
print(new_str)

Output

Jello World!


String Concatenation

  1. Create two string variables and initialize them with values.
  2. Concatenate the strings using the + operator.
  3. Print the concatenated string.

Python Program

str1 = "Hello"
str2 = " World!"
str3 = str1 + str2 # Concatenating strings
print(str3)

Output

Hello World!


Finding Substrings

  1. Create a string variable and initialize it with a value.
  2. Use the find method to find a substring.
  3. Print the position of the found substring.

Python Program

str = "Hello, world!"
pos = str.find("world") # Finding substring
if pos != -1:
    print(f"Found 'world' at position: {pos}")
else:
    print("Substring not found")

Output

Found 'world' at position: 7


String Length

  1. Create a string variable and initialize it with a value.
  2. Use the len function to get the length of the string.
  3. Print the length of the string.

Python Program

str = "Hello, world!"
print(f"Length of the string: {len(str)}")

Output

Length of the string: 13