Skip to content

Commit 4e3bf97

Browse files
authored
[Edit] Python: Strings (#7442)
* [Edit] Python: Strings * updated FAQs * fixed format ---------
1 parent 29ff8a5 commit 4e3bf97

File tree

1 file changed

+69
-49
lines changed

1 file changed

+69
-49
lines changed

content/python/concepts/strings/strings.md

Lines changed: 69 additions & 49 deletions
Original file line numberDiff line numberDiff line change
@@ -4,41 +4,43 @@ Description: 'A string is a sequence of characters contained within a pair of si
44
Subjects:
55
- 'Code Foundations'
66
- 'Computer Science'
7-
- 'Data Science'
87
Tags:
9-
- 'Strings'
8+
- 'Characters'
9+
- 'Data Types'
1010
- 'Formatting'
1111
- 'Lists'
12-
- 'Data Types'
13-
- 'Characters'
1412
CatalogContent:
1513
- 'learn-python-3'
1614
- 'paths/computer-science'
1715
---
1816

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:
2022

2123
```py
2224
message1 = "I am a string"
2325
message2 = 'I am also a string'
2426
```
2527

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:
2729

2830
| Example | String? |
2931
| -------------------------- | ------- |
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 |
3638

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.
3840

39-
## Accessing the Characters of a String
41+
## Accessing the Characters of a String in Python
4042

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:
4244

4345
```py
4446
myString = "Hello, World!"
@@ -52,38 +54,34 @@ print("var_2: " + var_2) # Output: var_2: World!
5254
print("var_3: " + var_3) # Output: var_3: ell
5355
```
5456

55-
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`:
5658

5759
```py
5860
name = "phillis"
5961
name[8] # Throws an IndexError
6062
```
6163

62-
## Multi-line Strings
64+
## Multi-line Strings in Python
6365

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:
6567

6668
```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."""
7472
```
7573

76-
## Escape Characters
74+
## Escape Characters in a String in Python
7775

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 `'`:
7977

8078
```py
8179
my_string = 'It's a lovely day!'
8280

8381
print(my_string)
8482
```
8583

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:
8785

8886
```shell
8987
File "main.py", line 1
@@ -99,17 +97,15 @@ The backslash will not be visible if the string is printed:
9997
```py
10098
my_string = 'It\'s a lovely day!'
10199
102-
print(my_string)
103-
# Output: It's a lovely day!
100+
print(my_string) # Output: It's a lovely day!
104101
```
105102

106103
This problem can be avoided by wrapping strings containing `'` characters in double quotes:
107104

108105
```py
109106
my_string = "It's a lovely day!"
110107

111-
print(my_string)
112-
# Output: It's a lovely day!
108+
print(my_string) # Output: It's a lovely day!
113109
```
114110

115111
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:
125121
```shell
126122
I am on top!
127123
I am on bottom.
128-
I am indented!
124+
I am indented!
129125
```
130126

131-
## Modifying Strings
127+
## Modifying a String in Python
132128

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`:
134130

135131
```py
136132
string_one = "Hello, "
137133
string_two = "World! "
138134
combo = string_one + string_two
139135

140-
print(combo)
141-
# Output: Hello, World!
136+
print(combo) # Output: Hello, World!
142137

143138
new_combo = combo * 2
144139

145-
print(new_combo)
146-
# Output: Hello, World! Hello, World!
140+
print(new_combo) # Output: Hello, World! Hello, World!
147141

148142
if "World" in new_combo:
149-
print("It's here!")
150-
# Output: It's here!
143+
print("It's here!") # Output: It's here!
151144
```
152145

153146
Strings can also be formatted with either of the following:
154147

155148
- 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).
157150

158-
## Comparing Strings
151+
## Comparing Strings in Python
159152

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:
161154

162155
| Operator | Term | Description |
163156
| :------: | :----------------------: | ---------------------------------------------------------------------------------------- |
164157
| `==` | Equal | Returns `True` if two strings are equal. |
165158
| `!=` | Not equal | Returns `True` if two strings are not equal. |
166-
| `<` | Less than | Returns `True` if the left string is lexically prior the right string. |
167-
| `>` | Greater than | Returns `True` is the left string comes lexically after the right string. |
159+
| `<` | Less than | Returns `True` if the left string is lexically prior to the right string. |
160+
| `>` | Greater than | Returns `True` if the left string comes lexically after the right string. |
168161
| `<=` | Less than or equal to | Returns `True` if the left string is equal to or lexically prior to the right string. |
169162
| `>=` | Greater than or equal to | Returns `True` if the left string is equal to or comes lexically after the right string. |
170163

171-
The following example demonstrates string comparison:
164+
This codebyte example demonstrates string comparison in Python:
172165

173166
```codebyte/python
174167
string_one = "Hello"
@@ -178,6 +171,33 @@ print(string_one > string_two)
178171
print(string_one < string_two)
179172
```
180173

181-
## Built-in String Methods
174+
## Frequently Asked Questions
175+
176+
### 1. How to concatenate two strings in Python?
177+
178+
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:
182197

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.
198+
- `.lower()`: Converts to lowercase
199+
- `.upper()`: Converts to uppercase
200+
- `.strip()`: Removes whitespace
201+
- `.replace()`: Replaces substrings
202+
- `.split()`: Splits the string into a list
203+
- `.find()`: Finds the index of a substring

0 commit comments

Comments
 (0)