Text in Python

0

Basics of Strings

In Python, strings are sequences of characters enclosed in either single (`'...'`) or double (`"..."`) quotes. This flexibility allows you to easily include quotes within your strings without escaping them:

```python
# Both are valid
single_quote_string = 'Hello, world!'
double_quote_string = "Hello, world!"
```

Special characters, such as newline (`\n`), behave the same in both types of quotes. To include quotes within a string without escaping, you can switch to the other quote type:

```python
quote_in_single = 'He said, "Hello!"'
quote_in_double = "It's a beautiful day."
```

To escape quotes within the same type, use a backslash (`\`):

```python
escaped_single = 'It\'s a beautiful day.'
escaped_double = "He said, \"Hello!\""
```

Raw Strings

Raw strings, prefixed with `r`, treat backslashes as literal characters. This is useful for regular expressions and file paths:

```python
raw_string = r"C:\Users\name\path"
```

Note: A raw string cannot end with an odd number of backslashes due to how escaping works.

Multi-line Strings

Triple quotes (`'''...'''` or `"""..."""`) allow strings to span multiple lines. Line breaks within the triple quotes are included in the string:

```python
multi_line_string = """This is a
multi-line string."""
```

To prevent a line break, end the line with a backslash:

```python
single_line = """This is a \
single-line string."""
```

String Operations

Strings can be concatenated using the `+` operator and repeated using `*`:

```python
concat = "Hello, " + "world!"
repeat = "Ha" * 3
```

Adjacent string literals are automatically concatenated:

```python
auto_concat = "Hello, " "world!"
```

However, this does not work with variables:

```python
var1 = "Hello, "
var2 = "world!"
# This will raise an error
auto_concat_variables = var1 var2
```

Use `+` for concatenating variables:

```python
concat_variables = var1 + var2
```

Indexing and Slicing

Strings can be indexed and sliced. Indexing retrieves individual characters, with the first character at index 0:

```python
s = "Python"
first_char = s[0]  # 'P'
```

Negative indices count from the right:

```python
last_char = s[-1]  # 'n'
```

Slicing retrieves substrings:

```python
substring = s[1:4]  # 'yth'
```

Omitted indices default to the start or end of the string:

```python
slice_from_start = s[:2]  # 'Py'
slice_to_end = s[2:]      # 'thon'
```

Immutability and Length

Strings are immutable. Any operation that modifies a string creates a new one:

```python
new_s = s.replace("P", "J")
```

The `len()` function returns the length of a string:

```python
length = len(s)  # 6
```

String Methods and f-strings

Strings come with numerous methods for transformation and searching. Additionally, f-strings (`f"..."`) allow embedded expressions:

```python
name = "Alice"
greeting = f"Hello, {name}!"
```
Tags

Post a Comment

0Comments
Post a Comment (0)