iheartcpp
iheartcpp

Reputation: 381

python regular expression case change

I'm looking for a more robust way to convert the string below. I want to find the first 3 letters of the 3 words and change the case. The words could be anything, right now I'm just using string replace for each lower case letter.

s1 = 'hello.crazy.world.txt'

s1 = s1.replace('h','H')

Upvotes: 0

Views: 168

Answers (4)

vaultah
vaultah

Reputation: 46603

str.title capitalizes groups of consecutive letters - you'll just have to exclude the extension.

One way to do that:

In [5]: name, ext = s.rsplit('.', 1)

In [6]: '{}.{}'.format(name.title(), ext)
Out[6]: 'Hello.Crazy.World.txt'

Upvotes: 5

Alex Huszagh
Alex Huszagh

Reputation: 14644

You could use str.capitalize

s1 = 'hello.crazy.world.txt'
out = '.'.join([i.capitalize() for i in s1.split('.')])

This capitalizes all the first letters, producing 'Hello.Crazy.World.Txt'.

If you would like to do it for the first three words only, you can use a slice, and then append the extension.

s1 = 'hello.crazy.world.txt'
split = s1.split('.')
extension = split[-1]
capitalized = [i.capitalize() for i in split[:-1]]
capitalized.append(extension)
out = '.'.join(capitalized)

This produces 'Hello.Crazy.World.txt'.

The advantages of using capitalize over title is title capitalizes every word following a period, if you have an item you would not like to capitalize, you can omit the item (such as the last item in this case).

A more compact way would be using list comprehension to capitalize each item, with the exception of the last item, merge the lists and join the result string in a single step.:

s1 = 'hello.crazy.world.txt'
split = s1.split('.')
out = '.'.join([i.capitalize() for i in split[:-1]] + [split[-1]])

Upvotes: 1

tobspr
tobspr

Reputation: 8376

The easiest solution is using .title():

>>> "hello.crazy.world.txt".title()
"Hello.Crazy.World.Txt"

Since you don't want to capitalize the last part, you'd do:

parts = "hello.crazy.world.txt".split(".")
result = '.'.join(parts[:-1]).title() + "." + parts[-1]

Upvotes: 1

2ps
2ps

Reputation: 15986

Although your question is ambiguous on this, I think you want something like this:

import os
st_filename = 'hello.crazy.world.txt'
st_base, st_ext = os.path.splitext(st_filename)
st_base = st_base.title()
st_filename = ''.join(st_base, st_ext)
# I am unsure if the splitext will work across platforms to be rejoined with join, but it seems to work on linux and Mac OS X

Upvotes: 0

Related Questions