You don't need regular expressions. Python has a built-in string method that does what you need:
mystring.replace(" ", "_")
Answer from rogeriopvl on Stack Overflowpython - How to replace whitespaces with underscore? - Stack Overflow
Replace space with underscore using python - Stack Overflow
pandas - How do I lowercase a string and also change space into underscore in python? - Stack Overflow
How to replace space with underscores using a regex in EPLAN?
You don't need regular expressions. Python has a built-in string method that does what you need:
mystring.replace(" ", "_")
Replacing spaces is fine, but I might suggest going a little further to handle other URL-hostile characters like question marks, apostrophes, exclamation points, etc.
Also note that the general consensus among SEO experts is that dashes are preferred to underscores in URLs.
import re
def urlify(s):
# Remove all non-word characters (everything except numbers and letters)
s = re.sub(r"[^\w\s]", '', s)
# Replace all runs of whitespace with a single dash
s = re.sub(r"\s+", '-', s)
return s
# Prints: I-cant-get-no-satisfaction"
print(urlify("I can't get no satisfaction!"))
Here's a generic approach that should work for you:
teststring = 'hello world this is just a test. don\'t mind me 123.'
# replace multiple spaces with one space
while ' ' in teststring:
teststring = teststring.replace(' ', ' ')
# replace space with underscore (_)
teststring = teststring.replace(' ', '_')
print(teststring)
assert teststring == "hello_world_this_is_just_a_test._don't_mind_me_123." # True
Using a file example:
fname = 'mah_file.txt'
with open(fname) as in_file:
contents = in_file.read()
while ' ' in contents:
contents = contents.replace(' ', ' ')
# write updated contents back to file
with open(fname, 'w') as out_file:
out_file.write(contents.replace(' ', '_'))
This opens the files, reads line by line, splits the line into two parts, and combines the two parts with an underscore. I stored it in a list that you can use to do your next step.
with open('nog_rename_update.txt') as f:
new_list = []
for line in f:
# split the line
split = line.split()
new_list.append(split[0]+"_"+split[1])
# print the list to see results
print(new_list)
#
# add code to loop through the new list and to write to a file
#
Use lower and replace on whitespace
df['type'] = df['type'].str.replace(' ','_').str.lower()
input:
df = pd.DataFrame({'type':['Ground Improvement']})
df
looks like this
type
0 Ground Improvement
output
type
0 ground_improvement
Just two lines: -
s = "Ground Improvement"
s = str.lower() # Converts the entire string to lower case
s = str.replace(' ', '_') # Replaces the spaces with _
And There you have ground_improvement stored in s!