Strings
Python hosting: Host, run, and code Python in the cloud!
In mathematics, variables often possess specific values such as numbers.
However, variables don’t always have to be numerical. At times, they can hold a character or a series of characters, commonly referred to as strings.
Python Programming Bootcamp: Go from zero to hero
Strings
Think of a string as a series of characters that can be indexed numerically:
Each character within a string can be accessed using its index number. Remember, collections in Python start with an index of 0.
1 | s = "Python" |
There are three ways to define strings: using single quotes (‘), double quotes (“), or triple quotes (“””).
For instance:
1 | s = 'hello' |
You can store the result of a method, like s = s.replace("world","python")
.
String Slices
The syntax to slice a portion of a string is:
1 | s[ startIndex : endIndex ] |
The startIndex
defaults to 0 (representing the first character) if not specified. The endIndex
would be the length of the string plus one.
1 | s = "Hello Python" |
String Manipulation
There are several methods available for string manipulation:
1 | s = "Hello Python" |
Comparison, Search, and Concatenation
Use the operator ==
to compare two strings. The in
keyword helps you search within a string. Plus, you can concatenate one string to another using the +
operator.
1 | sentence = "The cat is brown" |
Escape Characters
Python supports special characters, like ‘\n’ for a new line:
1 | str1 = "In Python,\nyou can use escape characters in strings.\nThese characters have special meaning." |
\n
: New Line\"
: Double Quote\'
: Single Quote\t
: Tab\\
: Backslash
Methods for Strings
Use the following methods to manipulate strings:
- capitalize(str): Capitalizes the first letter of the string.
- count(str): Counts the frequency of the given substring.
- find(str): Finds the position of the first occurrence of a substring.
- index(str): Like find, but raises an exception if not found.
- isdecimal(): Returns true if the string is purely decimal.
- isdigit(): Returns true if the string is composed of digits only.
- isnumeric(): Returns true if the string is numeric.
- lower(): Converts the string to lowercase.
- len(str): Returns the length of the string.
- upper(): Converts the string to uppercase.
- replace(old, new): Replaces the old substring with the new one.
Leave a Reply: