Python String Tutorials: Int to String, Add Leading Zero to Number

String literals in Python are surrounded by either single quotation marks, or double quotation marks.

Convert a number to a string

To convert an integer to a string, use the str() built-in function.


Add leading zero to single digit number

=> output : "05"
//for Python 3.6+

Get last n digits of a string

=> result: 21 
year = '2021'
=> result: 021 

Split a string

By default, split() takes whitespace as the delimiter.

s = "a b c"
list = s.split()
#output: ['a', 'b', 'c']

Split by first 1 whitespace only.

s = "a b c"
list = s.split(' ', 1)
#output: ['a', 'b c']

Format a string

lower() method converts all characters in a string into lowercase characters and returns it.

'Aa Bb'.lower() #outout: 'aa bb'

upper() method converts all characters in a string into uppercase characters and returns it.

'Upper case'.upper() #output: 'UPPER CASE'

swapcase() method converts all uppercase characters to lowercase of the given string, and vice versa.

'UPPER lower'.swapcase() #output: 'upper LOWER'

strip() removes both the leading and the trailing characters. lstrip() removes leading ones, rstrip() removes the trailing ones.

'  Hello   '.strip() #output: 'Hello'

Remove ‘b’ character in front of a string

b character appears in front of a string when you work with encoding and decoding. So to remove it , just decode the bytes.


Leave a Comment

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.