H e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
in
and not in
operatorsAn escape character is created by typing a backslash \
followed by the character you want to insert.
Escape character | Prints as |
---|---|
\' |
Single quote |
\" |
Double quote |
\t |
Tab |
\n |
Newline (line break) |
\\ |
Backslash |
A raw string entirely ignores all escape characters and prints any backslash that appears in the string.
%
operatorWe can use the %d
format specifier to convert an int value to a string:
If your are using Python 3.6+, string f-Strings
are the recommended way to format strings.
It is even possible to do inline arithmetic with it:
Rounding
Showing as Percentage
Number | Format | Output | description |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | Format float 2 decimal places |
3.1415926 | {:+.2f} | +3.14 | Format float 2 decimal places with sign |
-1 | {:+.2f} | -1.00 | Format float 2 decimal places with sign |
2.71828 | {:.0f} | 3 | Format float with no decimal places |
4 | {:0>2d} | 04 | Pad number with zeros (left padding, width 2) |
11 | {:11d} | 11 | Right-aligned (default, width 10) |
11 | {:<11d} | 11 | Left-aligned (width 10) |
11 | {:^11d} | 11 | Center aligned (width 10) |
upper()
, lower()
and title()
Transforms a string to upper, lower and title case:
isupper()
and islower()
methodsReturns True
or False
after evaluating if a string is in upper or lower case:
isX()
string methodsMethod | Description |
---|---|
isalpha() |
returns True if the string consists only of letters. |
isalnum() |
returns True if the string consists only of letters and numbers. |
isdecimal() |
returns True if the string consists only of numbers. |
isspace() |
returns True if the string consists only of spaces, tabs, and new-lines. |
istitle() |
returns True if the string consists only of words that begin with an uppercase letter followed by only lowercase characters. |
startswith()
and endswith()
(Optional)replace()
The replace()
function is like a “search and replace” operation in a word processor
join()
and split()
join()
The join()
method takes all the items in an iterable, like a list, dictionary, tuple or set, and joins them into a string. You can also specify a separator.
split()
The split()
method splits a string
into a list
. By default, it will use whitespace to separate the items, but you can also set another character of choice:
strip()
, rstrip()
, and lstrip()
\
) used to introduce special character sequences in a string, such as \n
for newline.r
that treats backslashes as literal characters rather than escape sequences.format()
method..2f
for two decimal places).f
that allows inline expression evaluation and formatting directly within the string.