PYTHON — Built-in String Functions in Python
Make it work, make it right, make it fast. — Kent Beck
Insights in this article were refined using prompt engineering methods.
PYTHON — Sorting Columns in a Python DataFrame
Built-in String Functions in Python
Python provides several built-in functions that are always available within the interpreter and can be used to work with strings and character data. In this article, we’ll explore a few of these functions and how they can be used. The functions we’ll cover are chr(), ord(), len(), and str().
chr() Function
The chr() function converts an integer to a character. Here are some examples of chr() in use:
>>> chr(97)
'a'
>>> chr(35)
'#'
>>> chr(32)
' '
>>> chr(129363)
'🥓'
ord() Function
The ord() function converts a character to an integer. Here are some examples of ord() in use:
>>> ord('a')
97
>>> ord(' ')
32
>>> ord('#')
35
>>> ord('€')
8364
>>> ord('🥓')
129363
len() Function
The len() function returns the length of a string. Here are some examples of len() in use:
>>> s = 'I am a string'
>>> len(s)
13
>>> s = ''
>>> len(s)
0
str() Function
The str() function returns a string representation of an object. Here are some examples of str() in use:
>>> str(49.2)
'49.2'
>>> str(3 + 29)
'32'
>>> a = str(3 + 29)
>>> a
'32'
>>> type(a)
<class 'str'>
For further learning, you can explore Basic Data Types in Python. Additionally, here are some resources on characters and encoding:
In summary, Python’s built-in string functions provide convenient ways to work with characters and strings. By using chr(), ord(), len(), and str(), you can manipulate and understand string and character data in Python easily.