Let’s go step by step and explain Python strings with beginner-friendly examples.


🔹 1. What is a String in Python?

A string is a sequence of characters enclosed in single quotes (”), double quotes (“”), or triple quotes (”’ or “””).

s1 = 'Hello'
s2 = "World"
s3 = '''This is also a string'''

Strings are immutable → once created, they cannot be changed in place.


🔹 2. Common String Methods and Usages

✅ (a) len() → Get length of string

text = "Python"
print(len(text))  # 6

✅ (b) Slicing → Extract part of a string

word = "Python"
print(word[0])    # 'P' (first character)
print(word[-1])   # 'n' (last character)
print(word[0:4])  # 'Pyth' (characters 0 to 3)
print(word[2:])   # 'thon' (from index 2 to end)

✅ (c) replace() → Replace part of string

msg = "I like Java"
new_msg = msg.replace("Java", "Python")
print(new_msg)  # I like Python

✅ (d) strip() → Remove extra spaces

data = "   hello world   "
print(data.strip())   # 'hello world'
print(data.lstrip())  # 'hello world   ' (only left)
print(data.rstrip())  # '   hello world' (only right)

✅ (e) split() → Break string into list

sentence = "apple,banana,orange"
fruits = sentence.split(",")
print(fruits)  # ['apple', 'banana', 'orange']

✅ (f) join() → Join list into string

words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)  # 'Python is fun'

🔹 3. Multi-line Strings

✅ (a) Using \ at the end of each line

If you want a long string without breaking it:

text = "This is a very long string \
that goes on the next line \
but is still considered one line."
print(text)
# Output: This is a very long string that goes on the next line but is still considered one line.

✅ (b) Using Triple Quotes (''' or """)

Triple quotes let you:

  • Write multi-line text
  • Include both single and double quotes inside easily
story = """He said, "Python is amazing!"
And I replied, 'Yes, absolutely!'"""
print(story)

This preserves line breaks and quotes.


🔹 4. Triple Quotes for Docstrings

A docstring is a special string used to document functions, classes, or modules.
They are written in triple quotes right after a function/class definition.

def greet(name):
    """
    This function greets the person whose name is passed as an argument.
    
    Parameters:
        name (str): The name of the person.
    
    Returns:
        str: Greeting message
    """
    return f"Hello, {name}!"
    
print(greet("Alice"))
  • help(greet) will display the docstring.
  • They make your code self-explanatory and are a best practice in Python.

Summary

  • len() → get length
  • slicing → extract parts
  • replace() → substitute text
  • strip() → remove spaces
  • split() & join() → convert between list and string
  • \ → continue string across lines
  • ''' or """ → multi-line strings, docstrings

Pages: 1 2 3 4 5 6


Discover more from HintsToday

Subscribe to get the latest posts sent to your email.

Posted in

Discover more from HintsToday

Subscribe now to keep reading and get access to the full archive.

Continue reading