Python:Strings
Jump to navigation
Jump to search
Strings are immutable, all methods return a new string
Formatting
Basic
- str1.replace(old,new[,cnt])
- In str1 replace old by new (cnt times)
- str1.join(list)
- Join list (or set or other sequence) with str1 as separator
- str1.split(sep[,max)
- Split string in to a list on sep into max + 1 elements (remainder is put in last element)
- str1.splitlines([keepends])
- Split on newline, with keepends the newline is preserved.
- str1.center(w)
- str1.ljust(w)
- str1.rjust(w)
- Put spaces around str1 to length 'w' is reached.
- str1.expandtabs(size)
- Replace tabs by 'size' number of spaces
Advanced
- str1.format(values)
- Fill in 'values' in string-fields ({}), if numbered fields can be in a different format than the values.
- If values are in a dict, they can be addressed by their key.
Code Example
"Value 1: {}, Value2: {}".format(1,2)
"Value 2: {1}, Value1: {0}".format(1,2)
dict1 = {'value1':1, 'value2':2}
"Value 2: {value2}, Value1: {value1}".format(dict1)
- {[field]
- spec}
- The format can be specified after the (optional) fieldnumber.
- <alignment><width>.<precision><type>
- Generic format specification. Anything not needed can be left out.
< | Left |
> | Right |
^ | Center |
= | Padding (after sign) |
# | Prepend for x, o and b types |
c | Character |
d | decimal |
f | Float |
% | Percent |
o | Octal |
x | Hexadecimal |
b | Binary |
e | Exponent |
g | Python chooses between decimal, float or exponent |