How can I check if a string ends with a period, or with a period followed by spaces, or if it is an empty string?

Question:

import re

def aaa(i):
    if(i == 0): a = ''
    elif(i == 1): a = 'Hola, como estás?.  '
    elif(i == 2): a = 'Yo estube programando algo'
    elif(i == 3): a = 'no esta mal ese celular, lo uso en la oficina.'

    return a

text, i_text = "", ""

for i in range(4):
    print(i)
    i_text = aaa(i)
    #HERE SHOULD BE THE REGEX OR SCORE VERIFIER LINE
    text = text + i_text + ". "

print(repr(text))  # --> output

How should I add the periods only when the string received from the example function aaa() is not a string ending with a period . , or is a string that only contains whitespace or directly have nothing (as is the case with the first one).

In such a case, instead of getting this output with the incorrectly made scores

'. Hola, como estás?.  . Yo estube programando algo. no esta mal ese celular, lo uso en la oficina.. '

The correct output should be:

'Hola, como estás?. Yo estube programando algo. no esta mal ese celular, lo uso en la oficina.'

It is very important that checking the points at the end of each i_text is done at each iteration, and not at the end of everything before using print()

Asked By: Matt095

||

Answers:

Here is an approach:

text = ""
for i in range(4):
    i_text = aaa(i).rstrip()
    if i_text and i_text[-1] not in ".,?":
        i_text += "."
    text += f"{i_text} "
print(repr(text.strip()))

Using re approach import re then subtitute

if i_text and i_text[-1] not in ".,?":

with

if i_text and not re.search(r"[s,.]+$", i_text):

'Hola, como estás?. Yo estube programando algo. no esta mal ese celular, lo uso en la oficina.'
Answered By: Jamiu S.

You can remove the whitespace using str.rstrip() and add a period conditionally:

i_text = i_text.rstrip()
if len(i_text) > 0:
    i_text = ''.join([i_text, '.' if i_text[-1] != '.' else '', ' '])
Answered By: B Remmelzwaal

You can do this by just stripping whitespace and checking if the last character is a period:

i_temp = i_text.rstrip()

if i_temp == "" or i_temp[-1] != ".":
    text = text + i_text + ". "

i_text.rstrip()[-1] will take the string, remove trailing whitespace (rstrip()) and get the last character ([-1]).

Answered By: gradiian