Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying strings in Python

Tags:

python

string

I have a string here in python '#b9d9ff'. How do I remove the hash symbol (#)?

like image 562
rectangletangle Avatar asked Feb 11 '26 22:02

rectangletangle


2 Answers

There are various trivially-different options. Each one does the same thing for your string but handles other strings differently.

# Strip any hashes on the left.
string.lstrip('#')

# Remove hashes anywhere in the string, not necessarily just from the front.
string.replace('#', '')

# Remove only the first hash in the string.
string.replace('#', '', 1)

# Unconditionally remove the first character, no matter what it is.
string[1:]

# If the first character is a hash, remove it. Otherwise do nothing.
import re
re.sub('^#', '', string)

(If you don't care which, use lstrip('#'). It is the most self-descriptive.)

like image 102
John Kugelman Avatar answered Feb 13 '26 17:02

John Kugelman


>>> '#bdd9ff'[1:]
'bdd9ff'
>>> '#bdd9ff'.replace('#', '')
'bdd9ff'
like image 41
ecik Avatar answered Feb 13 '26 15:02

ecik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!