Popular Searches
Popular Course Categories
Popular Courses

Creating and Accessing Strings

Creating and Accessing Strings

Python Data Structures — Strings, Lists, and Tuples

Creating and Accessing Strings in Python

Course: Python Programming

Topic: Creating and Accessing Strings

Course Link: Python Training Course at JustAcademy

Demo Link: Register for a Course Demo

Website: JustAcademy Homepage


1. Introduction to Strings in Python

A string is a sequence of characters used to represent text in Python. Strings can contain letters, numbers, spaces, punctuation marks, and special characters. Python uses the built-in str data type to store string values.

Strings are used in almost every type of application, including websites, data analysis, user authentication, reports, messaging systems, file processing, and database operations.

Examples of Strings

name = "Aarav"
city = "Mumbai"
message = "Welcome to Python!"
phone = "9876543210"
empty_text = ""

print(name)
print(city)
print(message)
print(phone)
print(empty_text)

Output:

Aarav
Mumbai
Welcome to Python!
9876543210

The phone variable is a string because it is enclosed in quotation marks. This is useful because phone numbers are identifiers rather than values that normally require arithmetic operations.

2. Creating Strings Using Single Quotes

Python allows strings to be created using single quotation marks (' '). Everything between the opening and closing quotation marks becomes part of the string, except for characters interpreted as escape sequences.

Example

language = 'Python'
course = 'Programming Fundamentals'
message = 'Learning Python is interesting.'

print(language)
print(course)
print(message)

Output:

Python
Programming Fundamentals
Learning Python is interesting.

Single quotes are convenient for short text values. However, if the text itself contains an apostrophe, you must choose suitable quotation marks or escape the apostrophe.

Example with an Apostrophe

message = 'Python is easy to learn.'
print(message)

sentence = 'It\'s a useful programming language.'
print(sentence)

Output:

Python is easy to learn.
It's a useful programming language.

The backslash in \' allows the apostrophe to appear inside a single-quoted string without ending the string early.

3. Creating Strings Using Double Quotes

Python also supports double quotation marks (" "). Single-quoted and double-quoted strings behave the same way in normal use. Choosing between them often depends on which quotation marks make the text easier to read.

Example

name = "Meera"
course = "Python Programming"
message = "Welcome to the course!"

print(name)
print(course)
print(message)

Output:

Meera
Python Programming
Welcome to the course!

Including an Apostrophe Without Escaping It

sentence = "It's a beautiful day."
print(sentence)

Output:

It's a beautiful day.

Because the string uses double quotes, the apostrophe does not terminate it.

Including Double Quotes Inside a String

message = "She said, \"Python is amazing!\""
print(message)

Output:

She said, "Python is amazing!"

The escape sequence \" allows a double quotation mark to be included inside a double-quoted string.

4. Creating Multiline Strings with Triple Quotes

Triple single quotes (''' ''') and triple double quotes (""" """) allow strings to span multiple lines. They are useful for paragraphs, documentation, messages, and text containing line breaks.

Example Using Triple Double Quotes

description = """Python is a programming language.
It is used for web development,
automation, and data analysis."""

print(description)

Output:

Python is a programming language.
It is used for web development,
automation, and data analysis.

Example Using Triple Single Quotes

address = '''Aarav Sharma
Flat 12, Green Residency
Mumbai, Maharashtra'''

print(address)

Output:

Aarav Sharma
Flat 12, Green Residency
Mumbai, Maharashtra

Triple-quoted strings preserve line breaks and indentation contained in the string. Keep this in mind when storing formatted text or building multiline messages.

5. Creating an Empty String

An empty string is a string containing zero characters. It is represented by two consecutive single quotes or two consecutive double quotes.

Example

first = ""
second = ''

print(first)
print(second)
print(len(first))
print(len(second))

Output:


0
0

Both variables contain empty strings, so their lengths are zero. Empty strings are useful as initial values for text variables, search results, and user-input processing.

6. Creating Strings Using the str() Function

The built-in str() function converts many Python objects into their string representation. It is particularly useful when displaying numeric values or combining values of different data types into a message.

Example

age = 25
price = 499.50
is_active = True

age_text = str(age)
price_text = str(price)
active_text = str(is_active)

print(age_text)
print(price_text)
print(active_text)

Output:

25
499.5
True

The result of str() is text. For example, str(25) produces the string "25", not the integer 25.

Combining a Number with Text

age = 25

message = "My age is " + str(age)
print(message)

Output:

My age is 25

Python does not automatically concatenate a string and an integer with the + operator. Convert the integer to a string or use an f-string.

7. Assigning Strings to Variables

A variable stores a reference to a string object. Python does not require you to declare a variable's type before assigning a string to it.

Example

student_name = "Rohan"
course_name = "Python"
learning_status = "Beginner"

print("Student:", student_name)
print("Course:", course_name)
print("Level:", learning_status)

Output:

Student: Rohan
Course: Python
Level: Beginner

Variable names should describe the information they store. Names such as student_name and course_name are more readable than unclear names such as x or abc.

8. Accessing Characters in a String

Python strings are sequences, so individual characters can be accessed using square brackets and an index. Python uses zero-based indexing, which means the first character has index 0, the second has index 1, and so on.

Python does not have a separate character data type. Accessing a single character from a string returns another string of length one.

Example

language = "Python"

print(language[0])
print(language[1])
print(language[2])
print(language[3])
print(language[4])
print(language[5])

Output:

P
y
t
h
o
n

The string "Python" contains six characters, so its valid positive indices are 0 through 5.

String Index Position Table

Character Positive Index Negative Index
P 0 -6
y 1 -5
t 2 -4
h 3 -3
o 4 -2
n 5 -1

9. Accessing Characters Using Negative Indexing

Negative indexing starts at the end of a string. The index -1 refers to the last character, -2 refers to the second-last character, and so on.

Example

language = "Python"

print(language[-1])
print(language[-2])
print(language[-3])
print(language[-4])
print(language[-5])
print(language[-6])

Output:

n
o
h
t
y
P

Negative indexing is useful when you need to access the last character without calculating the string's length.

Example: Get the Last Character

filename = "report.pdf"

last_character = filename[-1]

print("Last character:", last_character)

Output:

Last character: f

10. Finding the Length of a String

The built-in len() function returns the number of Unicode code points in a Python string. Spaces and punctuation count toward the length, as do letters and digits.

Example

text = "Python"

print(len(text))

Output:

6

Example Including Spaces

message = "Hello World"

print(len(message))

Output:

11

The space between Hello and World counts as one character in this string.

Example: Validate a Username Length

username = "aarav25"

if len(username) >= 5:
    print("Username length is acceptable.")
else:
    print("Username must contain at least 5 characters.")

Output:

Username length is acceptable.

In real applications, length validation is only one part of validation. The allowed characters, uniqueness, and other requirements may also need to be checked.

11. Accessing a Range of Characters Using Slicing

String slicing extracts a portion of a string. It uses a colon inside square brackets to specify a starting index and a stopping index.

Syntax

string[start:stop]
  • start: The index where extraction begins; it is included.
  • stop: The index where extraction ends; it is excluded.

Example

language = "Python"

print(language[0:2])
print(language[2:5])
print(language[1:4])

Output:

Py
tho
yth

For language[2:5], Python includes indices 2, 3, and 4 but excludes index 5. The resulting substring is "tho".

Example: Extract a First Name

full_name = "Aarav Sharma"

first_name = full_name[0:5]

print(first_name)

Output:

Aarav

This example works because the first name occupies indices 0 through 4. Slicing by fixed positions is appropriate only when the input format is known; for names with variable lengths, use methods such as split() when suitable.

12. Using Default Slice Positions

Python allows either the starting or stopping index to be omitted. When the start is omitted, slicing begins at the beginning of the string. When the stop is omitted, slicing continues to the end.

Example

language = "Python Programming"

print(language[:6])
print(language[7:])
print(language[:])

Output:

Python
Programming
Python Programming

language[:6] extracts the first six characters. language[7:] extracts the text from index 7 to the end. language[:] returns a string with the same content.

13. Using Negative Indices in Slicing

Negative indices can also be used in slice expressions to select text relative to the end of a string.

Example

language = "Python"

print(language[-3:])
print(language[:-2])
print(language[-5:-2])

Output:

hon
Pyth
yth

Negative slicing can make it convenient to extract suffixes, prefixes, or portions of text near the end of a string.

14. Using the Step Value in Slicing

A slice can include a third value called the step. The step determines how many index positions to move between selected characters.

Syntax

string[start:stop:step]

Example: Select Every Second Character

text = "PythonProgramming"

print(text[::2])

Output:

PtoPormig

The step of 2 selects every second character, beginning at index 0.

Example: Reverse a String

word = "Python"

reversed_word = word[::-1]

print(reversed_word)

Output:

nohtyP

A step of -1 traverses the string in reverse order and returns a reversed copy as a new string.

15. Accessing Characters with a for Loop

A for loop can iterate directly over a string, processing one character at a time. This is useful for counting characters, validating text, and examining the contents of a string.

Example

word = "Python"

for character in word:
    print(character)

Output:

P
y
t
h
o
n

Example: Display Characters with Their Positions

word = "Code"

for index, character in enumerate(word):
    print(index, character)

Output:

0 C
1 o
2 d
3 e

The enumerate() function provides each character together with its index, making it useful for inspecting a string without manually maintaining a counter.

16. Accessing User Input as a String

The built-in input() function reads a line of text from the user and returns it as a string. Even if the user types digits, the returned value is initially text.

Example

name = input("Enter your name: ")

print("Welcome,", name)
print("Your name contains", len(name), "characters.")

Example interaction:

Enter your name: Meera
Welcome, Meera
Your name contains 5 characters.

Example: Access the First Character of User Input

word = input("Enter a word: ")

if word:
    print("First character:", word[0])
else:
    print("You did not enter any text.")

The condition if word checks whether the string is non-empty. This prevents an IndexError that would occur if the program tried to access word[0] when the user entered an empty line.

17. Strings Are Immutable

Python strings are immutable, which means their characters cannot be changed in place after the string has been created. You can access characters and create modified strings, but you cannot assign a new character directly to an existing string index.

Incorrect Example

word = "Python"
word[0] = "J"

Result: Python raises a TypeError because string items do not support assignment.

Correct Example: Create a New String

word = "Python"
new_word = "J" + word[1:]

print(new_word)

Output:

Jython

The expression combines a new first character with a slice of the original string. It creates a new string instead of modifying the original one.

Example: Replace a Word

message = "I like Java"
updated_message = message.replace("Java", "Python")

print(message)
print(updated_message)

Output:

I like Java
I like Python

The replace() method returns a new string. The original variable remains unchanged unless the new result is assigned back to it.

18. Combining Strings Using Concatenation

Concatenation means joining two or more strings into a single string. Python uses the + operator for concatenation.

Example

first_name = "Aarav"
last_name = "Sharma"

full_name = first_name + " " + last_name

print(full_name)

Output:

Aarav Sharma

The space string " " is added between the two names so that the output is readable.

Example: Build a Message

course = "Python"
level = "Beginner"

message = "Course: " + course + ", Level: " + level

print(message)

Output:

Course: Python, Level: Beginner

19. Repeating Strings with the Multiplication Operator

The multiplication operator * can repeat a string a specified number of times. The repetition count must be an integer.

Example

text = "Hi! "

print(text * 3)

Output:

Hi! Hi! Hi! 

Example: Create a Separator

separator = "-" * 20

print(separator)
print("STUDENT REPORT")
print(separator)

Output:

--------------------
STUDENT REPORT
--------------------

String repetition is useful for separators, simple text layouts, and basic output formatting.

20. Formatting Strings with f-Strings

Formatted string literals, commonly called f-strings, allow you to place expressions and variable values directly inside a string. Start the string with f or F and place expressions inside curly braces.

Example

name = "Meera"
age = 22
course = "Python"

message = f"My name is {name}, I am {age} years old, and I am learning {course}."

print(message)

Output:

My name is Meera, I am 22 years old, and I am learning Python.

Example: Format a Price

product = "Keyboard"
price = 1299.5

print(f"Product: {product}")
print(f"Price: Rs. {price:.2f}")

Output:

Product: Keyboard
Price: Rs. 1299.50

The format specification :.2f displays the numeric value with two digits after the decimal point.

21. Common Errors When Creating and Accessing Strings

Error Cause Solution
Unterminated string literal A closing quotation mark is missing. Check that every opening quote has a matching closing quote.
IndexError An index is outside the valid range of the string. Check the string length before accessing an index.
TypeError during concatenation A string is combined with a non-string value using +. Use str() or an f-string to convert or format the value.
TypeError during assignment An attempt is made to change a string character using an index. Create a new string using concatenation, slicing, or a string method.
Unexpected spaces or line breaks Whitespace is part of the string value. Inspect the text and use methods such as strip() when appropriate.
Unexpected slice result The stop index is excluded from the slice. Remember that the start is included and the stop is excluded.
Empty-input error The code accesses a character when the string is empty. Check whether the string is non-empty before indexing.

22. Practical Exercises

Exercise 1: Create and Display Strings

Create variables for your name, city, favorite programming language, and a short message. Display each value using print().

Exercise 2: Access Characters

Store the string "Programming" in a variable. Print its first character, third character, last character, and second-last character.

Exercise 3: Find String Length

Ask the user to enter a sentence and display the total number of characters, including spaces and punctuation.

Exercise 4: Extract a Substring

Given the string "Python Programming", extract "Python" using slicing. Then extract "Programming".

Exercise 5: Reverse a String

Ask the user to enter a word and display it in reverse order using slicing.

Exercise 6: Create a Username Preview

Ask the user for a username. Display the first three characters and the total length, handling inputs shorter than three characters safely.

Exercise 7: Combine Strings

Ask for a first name and last name, combine them with a space, and display the full name.

Exercise 8: Replace Characters

Store a word in a variable and create a new string with a different first character using slicing and concatenation.

23. Mini Project: Student Profile Generator

This project demonstrates string creation, user input, indexing, length calculation, concatenation, and f-string formatting.

print("=== Student Profile Generator ===")

name = input("Enter your full name: ").strip()
city = input("Enter your city: ").strip()
course = input("Enter your course: ").strip()

if not name or not city or not course:
    print("Name, city, and course cannot be empty.")
else:
    profile = f"Student Name: {name}\nCity: {city}\nCourse: {course}"

    print("\n--- Student Profile ---")
    print(profile)
    print("Name Length:", len(name))
    print("First Character:", name[0])
    print("Last Character:", name[-1])

Example Interaction

=== Student Profile Generator ===
Enter your full name: Meera Shah
Enter your city: Mumbai
Enter your course: Python

--- Student Profile ---
Student Name: Meera Shah
City: Mumbai
Course: Python
Name Length: 10
First Character: M
Last Character: h

Project Explanation

  • The input() function accepts user information as strings.
  • The strip() method removes leading and trailing whitespace.
  • The conditional statement checks that the required fields are not empty.
  • The f-string combines the values into a formatted profile.
  • The \n escape sequence creates line breaks.
  • The len() function counts characters in the name.
  • Positive and negative indexing retrieve the first and last characters.

24. Interview Questions and Answers

Q1. What is a string in Python?

A string is an immutable sequence of Unicode code points represented by the built-in str type.

Q2. How can you create a string in Python?

You can use single quotes, double quotes, triple quotes, or the str() function to create or convert values into strings.

Q3. What is the difference between single and double quotes?

Both create strings with the same basic behavior. The choice often depends on which quotation marks make the content easier to represent.

Q4. What are triple-quoted strings used for?

They are useful for multiline text, paragraphs, and documentation strings.

Q5. What is string indexing?

Indexing accesses a character at a specific position. Positive indices begin at 0, while negative indices begin at -1 from the end.

Q6. What is string slicing?

Slicing extracts part of a string using the syntax string[start:stop:step]. The stop index is excluded.

Q7. How do you find the length of a string?

Use the built-in len() function.

Q8. Are Python strings mutable?

No. Strings are immutable, so their characters cannot be reassigned in place. A modified string must be created.

Q9. What happens if you access an invalid string index?

Python raises an IndexError. However, out-of-range slice boundaries are generally handled without raising an error.

Q10. How can you combine a string with an integer?

Convert the integer using str() or use an f-string to format the value into the text.

Q11. What does string[::-1] do?

It returns a new string with the characters in reverse order.

Q12. What does input() return?

The input() function returns the entered line as a string. Numeric input must be converted if arithmetic is required.

25. Quick Revision Checklist

  • Understand what strings are and how to create them.
  • Practice single, double, and triple quotation marks.
  • Use str() to convert values into strings.
  • Access individual characters using positive and negative indices.
  • Use len() to determine string length.
  • Extract substrings using slicing and step values.
  • Understand string immutability.
  • Combine strings using concatenation and f-strings.
  • Handle empty input and invalid indices safely.
  • Complete the practical exercises and mini project.

26. Conclusion

Creating and accessing strings is a fundamental skill in Python programming. Strings allow you to store, display, and process text. By learning how to create strings with quotation marks, use indexing and slicing, calculate string length, combine text, and work with immutable string values, you can build a strong foundation for more advanced topics such as string methods, validation, text processing, and file handling.

Continue your learning with the Python Training Course at JustAcademy. Visit the JustAcademy Homepage or register for a course demo to explore the available learning options.

Additional Reference: Official Python Tutorial – Strings

whatsapp