Python Sequence Type: Strings

0
Strings in Python are immutable sequences of Unicode characters. They support the common operations for sequence types, which include indexing, slicing, concatenation, repetition, and membership testing.

Indexing and Slicing

Python strings can be indexed and sliced to extract substrings:

```python
s = "Hello, World!"
print(s[0])  # Output: 'H'
print(s[7:12])  # Output: 'World'
print(s[-6:])  # Output: 'World!'
```

String Methods

Python provides a rich set of string methods for basic transformations and searching:
  • `str.upper()`: Converts all characters to uppercase.
  • `str.lower()`: Converts all characters to lowercase.
  • `str.replace(old, new)`: Replaces occurrences of a substring.
  • `str.find(sub)`: Returns the lowest index where the substring is found.
  • `str.split(sep)`: Splits the string at the separator.
Example:

```python
text = "hello, world"
print(text.upper())  # Output: 'HELLO, WORLD'
print(text.replace("world", "Python"))  # Output: 'hello, Python'
```

f-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings provide a way to embed expressions inside string literals using curly braces `{}`. They are prefixed with the letter `f`:

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

String Formatting with `str.format()`

The `str.format()` method allows for more advanced string formatting:

```python
text = "The value of pi is approximately {0:.2f}".format(3.14159)
print(text)  # Output: 'The value of pi is approximately 3.14'
```

Placeholders `{}` can be filled by positional arguments or keyword arguments. You can also use indices or named placeholders:

```python
text = "{name} has {n} apples".format(name="Alice", n=5)
print(text)  # Output: 'Alice has 5 apples'
```

Old-Style String Formatting

The old-style string formatting uses the `%` operator:

```python
value = 12.3456789
print("The value of Pi is approximately %.2f" % value)  # Output: 'The value of Pi is approximately 12.35'
```

This method allows for specifying the format directly within the string using format specifiers such as `%d`, `%s`, and `%f`.

Combining Methods

For comprehensive string manipulation, combining different methods can be very effective. For example:

```python
info = "Alice,30,Engineer"
name, age, profession = info.split(',')
formatted_output = f"{name} is a {profession} and is {age} years old."
print(formatted_output)  # Output: 'Alice is a Engineer and is 30 years old.'
```
Tags

Post a Comment

0Comments
Post a Comment (0)