Translate

Tuesday 6 February 2024

String data type in Python

 


Here's a comprehensive explanation of the string data type in Python:

What are strings?

  • Sequences of characters used to represent textual data.

  • Enclosed within single quotes (''), double quotes (""), or triple quotes (''' or """).

  • Used for names, messages, descriptions, code comments, etc.

Key characteristics:

  • Immutable: Cannot be modified in place. You create new strings with changes.

  • Ordered: Characters have a specific order, accessible by index (starting from 0).

  • Iterable: Can be looped through using for loops.



z = 20
print (z + "Rupees")

z = 10 print (str(z) + " rupees")

'vlr Training'
"vlr Training"

name = "vlr Training"
name
print(name)

Common operations:

  • Concatenation: Joining strings:
    Python
    first_name = "Alice"
    last_name = "Smith"
    full_name = first_name + " " + last_name  # Output: Alice Smith

  • Slicing: Extracting substrings:
    Python
    greeting = "Hello, world!"
    first_five = greeting[0:5# Output: Hello

  • Indexing: Accessing individual characters:
    Python
    message = "Python is awesome!"
    first_letter = message[0# Output: P

  • Formatting: Inserting variables into strings:
    Python
    name = "Bard"
    age = 30
    introduction = f"Hello, my name is {name} and I'm {age} years old."

  • Finding: Searching for substrings:
    Python
    text = "This is a sample text."
    is_found = "sample" in text  # True

  • Replacing: Substituting parts of a string:
    Python
    sentence = "I love coding in Python."
    new_sentence = sentence.replace("Python", "Java"# I love coding in Java.

  • Splitting: Dividing a string into a list of substrings:
    Python
    words = "apple, banana, cherry".split(","# Output: ["apple", "banana", "cherry"]

  • Upper/lower: Converting case:
    Python
    title = "the lord of the rings".title()  # Output: The Lord Of The Rings

  • Checking: Determining string properties:
    Python
    is_empty = "".isspace()  # True
    starts_with_python = "Python is cool".startswith("Python"# True

Additional notes:

  • Python has extensive string methods for various manipulations and transformations.

  • Use string formatting techniques (f-strings, format() method, etc.) for flexible output.

  • Consider using string libraries like string for advanced operations.

String data type in Python