How to ignore white space in string using regex?

Member

by lily , in category: Third Party Scripts , a month ago

How to ignore white space in string using regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by dedrick , a month ago

@lily 

To ignore white space in a string using regex, you can use the "s" (whitespace) pattern in your regular expression. This pattern will match any whitespace character such as spaces, tabs, and newlines.


For example, if you have a string "Hello World" and you want to ignore any whitespace in it, you can use the following regex pattern:

1
2
3
4
5
6
7
8
9
import re

# String with whitespace
string = "H e l l o  W o r l d"

# Remove whitespace using regex
clean_string = re.sub(r's', '', string)

print(clean_string)


In this example, the "s" pattern is used in the regular expression to match any whitespace characters in the string "H e l l o W o r l d" and remove them, resulting in the output "HelloWorld".