Python Strings

Python Strings Tutorial

A string in Python is a sequence of characters enclosed in single ('), double ("), or triple quotes (''' or """ """). Strings are immutable, meaning their values cannot be changed after creation.


1. Creating Strings

# Using single and double quotes
str1 = 'Hello'
str2 = "Python"

# Using triple quotes (for multi-line strings)
str3 = '''This is 
a multi-line 
string.'''

print(str1)  # Output: Hello
print(str3)

2. Accessing Characters in a String

Indexing (Positive & Negative)

s = "Python"
print(s[0])   # Output: P (First character)
print(s[-1])  # Output: n (Last character)
print(s[2])   # Output: t

Indexes start at 0 (left to right) and -1 (right to left).

Slicing Strings

s = "Hello, World!"
print(s[0:5])   # Output: Hello
print(s[:5])    # Output: Hello (Start from index 0)
print(s[7:])    # Output: World! (From index 7 to end)
print(s[-6:-1]) # Output: World

Slicing allows extracting a substring from a string.


3. String Length

s = "Python Programming"
print(len(s))  # Output: 18

len() returns the number of characters in the string.


4. String Methods

Python provides built-in methods to manipulate strings.

Changing Case

s = "hello python"
print(s.upper())  # Output: HELLO PYTHON
print(s.lower())  # Output: hello python
print(s.title())  # Output: Hello Python
print(s.capitalize())  # Output: Hello python

Checking Start and End

s = "Python is fun!"
print(s.startswith("Python"))  # Output: True
print(s.endswith("fun!"))      # Output: True

Finding and Replacing

s = "I love Python"
print(s.find("love"))  # Output: 2 (Index where "love" starts)
print(s.replace("Python", "coding"))  # Output: I love coding

Removing Spaces

s = "  Python  "
print(s.strip())  # Output: "Python" (Removes spaces from both ends)
print(s.lstrip())  # Output: "Python  " (Left strip)
print(s.rstrip())  # Output: "  Python" (Right strip)

Splitting and Joining

s = "apple,banana,grape"
words = s.split(",")  # Splits into a list
print(words)  # Output: ['apple', 'banana', 'grape']

joined = "-".join(words)  # Joins list elements with "-"
print(joined)  # Output: apple-banana-grape

5. String Concatenation & Repetition

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)  # Output: Hello World (Concatenation)
print(s1 * 3)  # Output: HelloHelloHello (Repetition)

6. String Formatting

Using format()

name = "Alice"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
# Output: My name is Alice and I am 25 years old.

Using f-strings (Python 3.6+)

name = "Bob"
age = 30
print(f"My name is {name} and I am {age} years old.")
# Output: My name is Bob and I am 30 years old.

7. Escape Characters

s = "Hello\nWorld!\tPython"
print(s)
# Output:
# Hello
# World!	Python

8. Checking String Content

s = "Python123"
print(s.isalpha())  # False (Contains numbers)
print(s.isdigit())  # False (Contains letters)
print(s.isalnum())  # True (Contains only letters and numbers)
print(s.isspace())  # False (Contains characters)

9. Reversing a String

s = "Python"
print(s[::-1])  # Output: nohtyP (Reversed)

10. Converting String to List and Vice Versa

s = "hello"
char_list = list(s)  # Convert string to list
print(char_list)  # Output: ['h', 'e', 'l', 'l', 'o']

new_str = "".join(char_list)  # Convert list back to string
print(new_str)  # Output: hello

Conclusion

  • Strings are immutable sequences of characters.
  • Python provides powerful built-in methods for string manipulation.
  • Use slicing, formatting, and escape characters to handle strings efficiently.

🚀 Master these concepts to work with strings effectively in Python!

Share on Google Plus

About It E Research

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment