2

It irks me not to be able to do the following in a single line. I've a feeling that it can be done through list comprehension, but how?

given_string = "first.second.third.None"
string_splitted = given_string.split('.')
string_splitted[-1] = "fourth"
given_string = ".".join(string_splitted)

Please note that the number of dots (.) in the given_string is constant (3). So i always want to replace the fourth fragment of the string.

Jai Sharma
  • 713
  • 1
  • 4
  • 17

5 Answers5

4

It seems like you should be able to do this without splitting into an array. Find the last . and slice to there:

> given_string = "first.second.third.None"
> given_string[:given_string.rfind('.')] + '.fourth'

'first.second.third.fourth'
Mark
  • 90,562
  • 7
  • 108
  • 148
2

You could try this:

given_string = "first.second.third.None"
given_string = ".".join(given_string.split('.')[:-1] + ["fourth"])
print(given_string)

Output:

first.second.third.fourth
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29
2

Try this one liner:-

print (".".join(given_string.split(".")[:-1]+["Fourth"]))

Output:

first.second.third.Fourth
nandal
  • 2,544
  • 1
  • 18
  • 23
0

You could use rsplit. This would work no matter how many dots precede the last split

given_string = "first.second.third.None"
string_splitted = given_string.rsplit('.', 1)[0] + '.fourth'

print(string_splitted)
first.second.third.fourth
Andrew
  • 950
  • 7
  • 24
0
my_string = "first.second.third.None"
my_sub = re.sub(r'((\w+\.){3})(\w+)', r'\1fourth', my_string)
print(my_sub)
first.second.third.fourth

A good explanation of this style is here: How to find and replace nth occurence of word in a sentence using python regular expression?

Car
  • 337
  • 2
  • 4
  • 14