Skip to main content

Working with Strings

In Python, a string is a sequence of characters. It's one of the basic data types in Python and is very commonly used in a variety of programming tasks. In this tutorial, we will discuss how to create, access, modify, and manipulate strings in Python.

Creating Strings

In Python, you can create a string by enclosing a sequence of characters within single quotes (' ') or double quotes (" ").

string1 = 'Hello, World!'
string2 = "Python is Fun!"

You can also create a string with triple quotes (''' ''' or """ """). This is useful when you want to create a string that spans multiple lines.

multiline_string = """This is a
multiline
string."""

Accessing Characters in a String

You can access characters in a string by using indexing. Indexing in Python starts from 0.

string = 'Python'
print(string[0]) # Output: P

You can also use negative indexing to access characters from the end of the string.

string = 'Python'
print(string[-1]) # Output: n

String Slicing

In Python, you can also access a range of characters in a string. This is known as slicing.

string = 'Python'
print(string[0:3]) # Output: Pyt

In the above example, 0:3 is a slice that starts at index 0 and ends at index 3. Note that the start index is inclusive, but the end index is exclusive.

Modifying Strings

Strings in Python are immutable. This means that once a string is created, it cannot be changed. However, you can create a new string based on an existing one.

string = 'Python'
new_string = string + ' Programming'
print(new_string) # Output: Python Programming

String Methods

Python provides several built-in methods that you can use to perform various operations on strings.

  • upper(): Converts all the characters in a string to upper case.
  • lower(): Converts all the characters in a string to lower case.
  • strip(): Removes leading and trailing white spaces from a string.
  • replace(old, new): Replaces all occurrences of the old substring with the new substring.
  • split(separator): Splits a string into a list of substrings.

Here are some examples:

string = ' Python Programming '

print(string.upper()) # Output: PYTHON PROGRAMMING
print(string.lower()) # Output: python programming
print(string.strip()) # Output: Python Programming
print(string.replace(' ', '-')) # Output: -Python-Programming-
print(string.split(' ')) # Output: ['', 'Python', 'Programming', '']

In this tutorial, we covered some of the basics of working with strings in Python. There are many more things you can do with strings, and as you continue your Python journey, you will get to explore them. Happy coding!