You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: content/python/concepts/strings/strings.md
+69-49Lines changed: 69 additions & 49 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,41 +4,43 @@ Description: 'A string is a sequence of characters contained within a pair of si
4
4
Subjects:
5
5
- 'Code Foundations'
6
6
- 'Computer Science'
7
-
- 'Data Science'
8
7
Tags:
9
-
- 'Strings'
8
+
- 'Characters'
9
+
- 'Data Types'
10
10
- 'Formatting'
11
11
- 'Lists'
12
-
- 'Data Types'
13
-
- 'Characters'
14
12
CatalogContent:
15
13
- 'learn-python-3'
16
14
- 'paths/computer-science'
17
15
---
18
16
19
-
A string is a sequence of characters contained within a pair of single quotes (`'`) or double quotes(`"`). Strings can store words, sentences, or whole paragraphs. They can be any length and can contain letters, numbers, symbols, and spaces.
17
+
A **string** in Python is a sequence of characters contained within a pair of single quotes (`'`) or double quotes(`"`). Strings can store words, sentences, or whole paragraphs. They can be of any length and can contain letters, numbers, symbols, and spaces.
18
+
19
+
## Creating a String in Python
20
+
21
+
Here's how a string in Python can be created:
20
22
21
23
```py
22
24
message1 ="I am a string"
23
25
message2 ='I am also a string'
24
26
```
25
27
26
-
Other [data types](https://www.codecademy.com/resources/docs/python/data-types) such as `integers`, `doubles`, and `booleans` can also be `strings` if they are wrapped in quotes.
28
+
Other [data types](https://www.codecademy.com/resources/docs/python/data-types) such as integers, float, and booleans can also be strings if they are wrapped in quotes:
27
29
28
30
| Example | String? |
29
31
| -------------------------- | ------- |
30
-
| "2" (with double-quotes) | Yes ✅|
31
-
| '3.6' (with single-quotes) | Yes ✅|
32
-
| "True" (also in quotes) | Yes ✅|
33
-
| 7 (integer) | No ❌|
34
-
| Hello (no quotes) | No ❌|
35
-
| True (boolean) | No ❌|
32
+
| "2" (with double-quotes) | Yes |
33
+
| '3.6' (with single-quotes) | Yes |
34
+
| "True" (also in quotes) | Yes |
35
+
| 7 (integer) | No |
36
+
| Hello (no quotes) | No |
37
+
| True (boolean) | No |
36
38
37
-
Strings are immutable; they cannot change. Every time an operation is performed on a string, a new string is created in memory.
39
+
Strings are immutable, meaning they cannot change. Every time an operation is performed on a string, a new string is created in memory.
38
40
39
-
## Accessing the Characters of a String
41
+
## Accessing the Characters of a String in Python
40
42
41
-
Strings in Python are technically a type of [list](https://www.codecademy.com/resources/docs/python/lists) — one in which each character is a separate element. This means each character in a string can be individually accessed by index, like with the elements in a list:
43
+
A string in Python is a sequence of characters. Like [lists](<(https://www.codecademy.com/resources/docs/python/lists)>), strings support indexing and slicing. This means each character in a string can be individually accessed by index, like with the elements in a list:
If an attempt is made to access an index out of bounds, it will return an `IndexError`.
57
+
If an attempt is made to access an index out of bounds, it will return an `IndexError`:
56
58
57
59
```py
58
60
name ="phillis"
59
61
name[8] # Throws an IndexError
60
62
```
61
63
62
-
## Multi-line Strings
64
+
## Multi-line Strings in Python
63
65
64
-
Strings can be long or short. For longer text, a multi-line string can be used. Multi-line strings begin and end with three single or double quotes:
66
+
A string in Python can be long or short. For longer text, a multi-line string can be used. Multi-line strings begin and end with three single or double quotes:
65
67
66
68
```py
67
-
my_string ="""If it were done when 'tis done, then 'twere well
68
-
It were done quickly: if the assassination
69
-
Could trammel up the consequence, and catch
70
-
With his surcease success; that but this blow
71
-
Might be the be-all and the end-all here,
72
-
But here, upon this bank and shoal of time,
73
-
We'ld jump the life to come."""
69
+
my_string ="""This is a
70
+
multi-line
71
+
string."""
74
72
```
75
73
76
-
## Escape Characters
74
+
## Escape Characters in a String in Python
77
75
78
-
Sometimes a string may have a character that Python tries to interpret, such as `'`.
76
+
Sometimes, a string in Python may have a character that Python tries to interpret, such as `'`:
79
77
80
78
```py
81
79
my_string ='It's a lovely day!'
82
80
83
81
print(my_string)
84
82
```
85
83
86
-
This will raise an error, because the interpreter thinks the second `'` marks the end of the string.
84
+
This will raise an error, because the interpreter thinks the second `'` marks the end of the string:
87
85
88
86
```shell
89
87
File "main.py", line 1
@@ -99,17 +97,15 @@ The backslash will not be visible if the string is printed:
99
97
```py
100
98
my_string = 'It\'s a lovely day!'
101
99
102
-
print(my_string)
103
-
# Output: It's a lovely day!
100
+
print(my_string) # Output: It's a lovely day!
104
101
```
105
102
106
103
This problem can be avoided by wrapping strings containing `'` characters in double quotes:
107
104
108
105
```py
109
106
my_string ="It's a lovely day!"
110
107
111
-
print(my_string)
112
-
# Output: It's a lovely day!
108
+
print(my_string) # Output: It's a lovely day!
113
109
```
114
110
115
111
Python also has a series of non-printing characters that can modify strings. For example, `\n` adds a new line and `\t` adds a tab:
@@ -125,50 +121,47 @@ This will output:
125
121
```shell
126
122
I am on top!
127
123
I am on bottom.
128
-
I am indented!
124
+
I am indented!
129
125
```
130
126
131
-
## Modifying Strings
127
+
## Modifying a String in Python
132
128
133
-
Python has special [operators](https://www.codecademy.com/resources/docs/python/operators) to modify strings. For example, `+` can be used to concatenate strings, and `*` can be used to multiply a string. The keyword `in` can be used to see if a given character or substring exists in a `string`.
129
+
Python has special [operators](https://www.codecademy.com/resources/docs/python/operators) to modify strings. For example, `+` can be used to concatenate strings and `*` can be used to multiply a string. The keyword `in` can be used to see if a given character or substring exists in a `string`:
Strings can also be formatted with either of the following:
154
147
155
148
- The `f/F` flag (placed before the opening quotation mark).
156
-
- The [.format()](https://www.codecademy.com/resources/docs/python/strings/format) method (requires manually adding placeholders).
149
+
- The [`.format()`](https://www.codecademy.com/resources/docs/python/strings/format) method (requires manually adding placeholders).
157
150
158
-
## Comparing Strings
151
+
## Comparing Strings in Python
159
152
160
-
Python can use comparison [operators](https://www.codecademy.com/resources/docs/python/operators) to compare the contents of two strings. The operators behave as they do with numeric arguments:
153
+
Python can use comparison operators to compare the contents of two strings. The operators behave as they do with numeric arguments:
You can use the `+` operator or `.join()` method to concatenate strings in Python:
179
+
180
+
```py
181
+
"Hello"+""+"World"# Using +
182
+
"".join(["Hello", "World"]) # Using join()
183
+
```
184
+
185
+
### 2. How can I slice a string in Python?
186
+
187
+
String slicing in Python uses the format `string[start:stop:step]`:
188
+
189
+
```py
190
+
text ="HelloWorld"
191
+
print(text[1:5]) # Output: ello
192
+
```
193
+
194
+
### 3. What are the 4 string functions in Python?
195
+
196
+
Here are some common Python string methods:
182
197
183
-
Python has a number of built-in string methods that manipulate strings. However, when these methods are called, the original string will not be changed, so any modifications will need to be saved to a new variable. A few useful built-in string methods are listed below.
0 commit comments