Geek Slack

Introduction to Python
    About Lesson



    Python Strings


    Python Strings

    In Python, a string is a sequence of characters enclosed within single quotes '' or double quotes "".

    1. Creating Strings

    You can create strings by enclosing characters within single quotes or double quotes.

    Example:

    single_quoted_string = 'Hello, World!'
    double_quoted_string = "Python is fun!"

    2. Accessing Characters

    You can access individual characters of a string using indexing.

    Example:

    string = "Python"
    first_char = string[0]    # Accessing the first character
    last_char = string[-1]    # Accessing the last character

    3. String Slicing

    You can extract a substring from a string using slicing.

    Example:

    string = "Python"
    substring = string[1:4]    # Extracting characters from index 1 to index 3

    4. String Concatenation

    You can concatenate (combine) two or more strings using the + operator.

    Example:

    string1 = "Hello"
    string2 = "World"
    combined_string = string1 + " " + string2

    5. String Methods

    Python provides various methods for working with strings, such as upper(), lower(), strip(), split(), join(), and many more.

    Example:

    string = "   Hello, World!   "
    uppercase_string = string.upper()
    lowercase_string = string.lower()
    stripped_string = string.strip()
    words = string.split(",")

    6. String Formatting

    You can format strings using the format() method or f-strings (formatted string literals).

    Example:

    name = "Alice"
    age = 30
    formatted_string = "My name is {} and I am {} years old.".format(name, age)
    f_string = f"My name is {name} and I am {age} years old."

    Conclusion

    Strings are a fundamental data type in Python used to represent text. Understanding how to create, manipulate, and format strings is essential for programming in Python.