Python Strings

  • Read
  • Discuss

Introduction

A string is a sequence of characters. In Python, strings are represented by enclosing a sequence of characters in single or double quotes.

For example:

"Hello, World!"
'Hello, World!'

Both of the above examples are valid strings in Python.

Creating Strings

To create a string in Python, you can use either single or double quotes. For example:

string1 = "Hello, World!"
string2 = 'Hello, World!'

Both of these create a string with the value “Hello, World!”.

You can also use triple quotes to create a multi-line string

For example:

string3 = """
This is a multi-line
string. It can span multiple
lines and still be treated as
a single string.
"""

Accessing Characters in a String

You can access individual characters in a string using indexing. In Python, indexing starts at 0. So, to access the first character in a string, you would use an index of 0.

For example:

string1 = "Hello, World!"
print(string1[0])  # Output: "H"
print(string1[1])  # Output: "e"

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

For example:

print(string1[-1])  # Output: "!"
print(string1[-2])  # Output: "d"

Slicing Strings

You can use slicing to access a range of characters in a string. To slice a string, you can use the following syntax:

string[start:end:step]
  • start: The index of the first character to include in the slice (default is 0).
  • end: The index of the first character to exclude from the slice (default is the length of the string).
  • step: The number of characters to skip between each character in the slice (default is 1).

For example:

string1 = "Hello, World!"
print(string1[0:5])  # Output: "Hello"
print(string1[6:12])  # Output: "World"
print(string1[::2])  # Output: "Hlo ol!" (every second character)

Modifying Strings

Strings are immutable in Python, which means that you cannot modify them directly. However, you can create a new string that is a modified version of an existing string.

For example:

string1 = "Hello, World!"
string2 = string1[:5] + "Python" + string1[12:]
print(string2)  # Output: "Hello, Python!"

String Methods

Python provides a number of built-in methods for working with strings. Here are some common ones:

  • len(string): Returns the length of the string.
  • string.lower(): Returns the string in lowercase.
  • string.upper(): Returns the string in uppercase.
  • string.strip(): Removes leading and trailing whitespace from the string.

Leave a Reply

Scroll to Top