Header Ads Widget

Ticker

6/random

Python Strings

Python Strings


 In Python, strings are used to represent text and are defined using single (' '), double (" "), or triple (''' ''' or """ """) quotes. Here are some examples:


1. Creating Strings:

   ```python

   single_quoted = 'Hello, Python!'

   double_quoted = "Welcome to Python!"

   triple_quoted = '''This is a

   multiline

   string.'''

   ```

2. Accessing Characters:

   ```python

   message = "Python"

   first_char = message[0]    # 'P'

   third_char = message[2]    # 't'

   ```

3. String Concatenation:

   ```python

   str1 = "Hello"

   str2 = "Python"

   combined_str = str1 + ", " + str2  # "Hello, Python"

   ```

4. String Methods:

   ```python

   greeting = " Hello, Python!  "

   length = len(greeting)      # Length of the string

   upper_case = greeting.upper()    # Convert to uppercase

   lower_case = greeting.lower()    # Convert to lowercase

   stripped = greeting.strip()      # Remove leading and trailing whitespaces

   ```

5. String Formatting:

   ```python

   name = "Alice"

   age = 30

   sentence = "My name is {} and I am {} years old.".format(name, age)

   ```

6. String Slicing:

   ```python

   phrase = "Python is powerful"

   substring = phrase[7:13]  # Extracts "is pow"

   ```

These examples showcase various operations you can perform with strings in Python. Strings are versatile and support many methods and operations for manipulation and formatting. Let me know if you have specific questions or if you'd like more examples!

Post a Comment

0 Comments