CodeSutraHub

Strings in Python

A string is a sequence of characters. In Python, strings are a data type used to store text data. Strings can be created using single quotes (' '), double quotes (" "), or triple quotes (''' ''' or """ """). In Python, the str data type represents strings. The str type is a built-in data type in Python.

Creating Strings

Strings can be created using single quotes, double quotes, or triple quotes.
Single quotes and double quotes are used to create single-line strings. Triple quotes are used to create multi-line strings.

Examples of Creating Strings in Python


# Single quotes
string1 = 'Welcome to Python World'

# Double quotes
string2 = "Python is Powerful"

# Triple quotes
string3 = '''This is a multi-line
string.'''
        

Creating Strings from Other Data Types

The str() function is used to create strings from other data types.

# Creating string from integer
num = 100
string_from_num = str(num)
print("String from integer:", string_from_num)  # Output: 100

# Creating string from float
flt = 10.5
string_from_flt = str(flt)
print("String from float:", string_from_flt)  # Output: 10.5
        

String Operations using + and * in Python


# Concatenation
string1 = "Welcome to"
string2 = "Python World"
result = string1 + " " + string2
print("Concatenation:", result)  # Output: Welcome to Python World

# Repetition
string1 = "hello"
result = string1 * 3
print("Repetition:", result)  # Output: hello hello hello

Note:
The + operator is used for concatenation, and the * operator is used for repetition.
Other arithmetic operators cannot be directly applied to strings.
        

String Indexing in Python

Strings in Python are indexable. Individual characters in a string can be accessed using indexes.

# Indexing
string = "Indexing"
first_char = string[0]
print("First character:", first_char)  # Output: I

Note:
Indexing starts from 0.
string[0] refers to the first character, string[1] to the second character, and so on.
        
Negative indexing allows you to access characters from the end of the string. string[-1] refers to the last character, string[-2] to the second last character, and so on.

# Negative Indexing
string = "Indexing"
last_char = string[-1]
print("Last character:", last_char)  # Output: g
        

String Slicing

In Python, strings can be sliced, meaning a portion of the string can be extracted. Slicing is done using start and end indexes.
Syntax:
string[start:end]
start indicates the starting index (inclusive).
end indicates the ending index (exclusive).

# Slicing
string = "Slicing"
substring = string[1:4]
print("Substring:", substring)  # Output: lic
        
If the start value is omitted, it defaults to 0.

# Slicing from start to specified length
string = "Slicing"
result = string[:4]
print("Start Omitted Slice:", result)  # Output: Slic
        
If the end value is omitted, it defaults to the length of the string.

# Slicing from specified position to end
string = "Slicing"
result = string[3:]
print("End Omitted Slice:", result)  # Output: cing
        
Negative values can also be used as slice indexes.

# Slicing with negative indices
string = "Slicing"
negative_slice = string[-5:-2]
print("Negative Slice:", negative_slice)  # Output: ici
        

String Methods in Python

Python provides many built-in string methods for string manipulation and processing.

# Examples of string methods
string = "Welcome to Python world"

# Convert to uppercase
upper_string = string.upper()
print("Uppercase:", upper_string)

# Convert to lowercase
lower_string = string.lower()
print("Lowercase:", lower_string)

# Find substring
index = string.find("Python")
print("Index of 'Python':", index)

# Replace substring
replaced_string = string.replace("world", "Language")
print("Replaced String:", replaced_string)

# Split string
split_string = string.split(" ")
print("Split String:", split_string)
        

String Formatting

In Python, f-strings are used for string formatting.

# Examples of string formatting
name = "NameXXXX"
age = 30

# Using f-strings
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)
        
Here
The prefix f indicates an f-string. Variables placed inside curly braces {} are directly embedded into the string. This makes string formatting simple and improves code readability.

Reading Data in Python

In Python, the input() function is used to read data from the keyboard. This function takes input from the user and always returns a string.
Syntax:
input(prompt)
The prompt is the message displayed to the user. Example: input("Enter your name: ")

Examples of Reading Data using input() Function


name = input("Enter your student name: ")
marks = input("Enter student marks: ")
print(f"Student Name: {name}, Marks: {marks}")
        

What We Have Learned

  • Strings in Python
  • Arithmetic and Assignment Operators in Python will be covered in the next topic

Watch the following Video for Strings in Python