import re
def contains_required_phrases(text: str) -> bool:
"""
Return True if *text* contains:
1. the word "baccalaureat"
AND
2. either "releve de notes" or "releve des notes"
The check is case‑insensitive and works even if there is extra whitespace
(e.g. multiple spaces or line‑breaks) between the words.
"""
# Normalise the string: strip leading/trailing spaces and collapse whitespace
normalized = re.sub(r'\s+', ' ', text.strip()).lower()
# Required substrings (already lower‑cased)
has_bac = 'baccalaureat' in normalized
has_releve = ('releve de notes' in normalized) or ('releve des notes' in normalized)
return has_bac and has_releve
# ----------------------------------------------------------------------
# Example usage
if __name__ == "__main__":
examples = [
"J’ai reçu mon Baccalaureat ainsi que le relevé de notes.",
"Le baccalaureat et le relevé des notes sont prêts.",
"Il n’y a que le baccalaureat ici.",
"Seul le relevé de notes est disponible.",
"BACCALAUREAT RELEVE DE NOTES", # irregular spacing
]
for i, s in enumerate(examples, 1):
print(f"{i:02d}: {contains_required_phrases(s)} -> {s}")
Collapses any sequence of whitespace characters (spaces, tabs, newlines) into a single space.
Converts everything to lower‑case so the test is case‑insensitive.
Checks
python
has_bac = 'baccalaureat' in normalized
has_releve = ('releve de notes' in normalized) or ('releve des notes' in normalized)
has_bac is True when the word baccalaureat appears anywhere.
has_releve is True when either of the two possible “relevé … notes” phrases appears.
Result
The function returns True only when both conditions are satisfied.
Feel free to adapt the function (e.g., use regular expressions for more flexible matching, handle accents, etc.) to fit the exact needs of your project.
The problem
You have a string that contains the characters “\” and “n” (e.g. "Hello\\nWorld").
When you print() it you see the literal text \n instead of a line‑break:
python
>>> s = "Hello\\nWorld"
>>> print(s)
Hello\nWorld # ← not a real line break
You want the visual line break (\n → newline) when the string is printed.
1. Replace the escaped sequence with a real newline
The simplest way is to turn the two‑character sequence \n into an actual newline character \n (ASCII 10) before printing.
python
def show_with_breaks(txt: str) -> None:
# Convert the literal "\n" into a real newline
txt = txt.replace(r'\n', '\n')
print(txt)
python
# Demo
s = "Hello\\nWorld"
show_with_breaks(s)
Output
code
Hello
World
2. Using bytes.decode('unicode_escape') (handles many escaped codes)
If the string may contain other escaped sequences (\t, \\, \u00e9, …) you can let Python decode the unicode‑escape encoding:
python
def decode_escapes(txt: str) -> str:
# Encode to bytes, then decode using the unicode‑escape codec
return txt.encode('utf-8').decode('unicode_escape')
python
s = r"Line1\nLine2\tTabbed\\Backslash\u00e9"
print(decode_escapes(s))
Output
code
Line1
Line2 Tabbed\Backslashé
Why r prefix?
Using a raw string (r"…") prevents Python itself from turning \n into a newline when the literal is created, so the string really contains the two characters \ and n.
3. print with sep and end (when you control the pieces yourself)
If you already have the parts you want to print separately, you can let print insert the line break for you:
Or, if you want a custom line break (e.g., Windows \r\n):
python
print(part1, part2, sep='\r\n')
4. sys.stdout.write – no automatic newline
print automatically adds a newline after the whole call (unless you specify end='').
If you want exact control over what gets written, use sys.stdout.write:
python
import sys
s = "Hello\\nWorld"
sys.stdout.write(s.replace(r'\n', '\n'))
No extra newline is appended, only the ones you embed yourself.
5. Quick one‑liner for REPL / scripts
If you just need a one‑liner in a script or the interactive interpreter:
python
print("Hello\\nWorld".replace(r'\n', '\n'))
TL;DR – What to use
Situation
Recommended method
Only \n needs conversion
s.replace(r'\n', '\n')
Many escaped sequences (\t, \uXXXX, etc.)
s.encode().decode('unicode_escape')
You have separate arguments
print(arg1, arg2, sep='\n')
Full control over output (no auto‑newline)
sys.stdout.write(...)
Pick the one that matches the complexity of your input string. Happy coding!
Below is a self‑contained example that shows how to pull out the text that appears on the same line before a given substring (only when that substring is present).
The solution works for:
a single‑line string or a multi‑line document (e.g. the contents of a text file)
any number of matches – it can return the first one, all of them, or a list of the preceding fragments
case‑insensitive searches (optional)
1. Core function – text_before_substring
python
import re
from typing import List, Tuple, Iterable, Optional
def text_before_substring(
source: str,
needle: str,
*,
case_insensitive: bool = False,
return_all: bool = False,
include_newline: bool = False,
) -> Optional[Iterable[Tuple[int, str]]]:
"""
Return the text that appears on the same line *before* ``needle``.
Parameters
----------
source : str
The whole document (may contain many lines).
needle : str
The substring you are looking for.
case_insensitive : bool, default False
If True, the search ignores case.
return_all : bool, default False
If True, returns a generator of all matches; otherwise only the
first match is returned.
include_newline : bool, default False
If True, the returned fragment includes the line‑break that ends the line.
(Useful when you want the exact slice of the original string.)
Returns
-------
If ``return_all`` is False:
``None`` – needle not found anywhere
``(line_no, text)`` – line number (1‑based) and the preceding text
If ``return_all`` is True:
generator yielding ``(line_no, text)`` for every match.
Example
-------
>>> doc = "alpha BETA gamma\\ndelta needle here\\nfinal line"
>>> text_before_substring(doc, "needle")
(2, 'delta ')
"""
# Build the regex pattern:
# ^.*?(?=needle) – everything from start of line up to (but not including) needle
# .*? – lazy so we stop at the first occurrence on each line
# (?=needle) – a look‑ahead that ensures needle is right after the captured part
# (.*) – optional: capture the rest of the line if you need it later
flags = re.MULTILINE
if case_insensitive:
flags |= re.IGNORECASE
esc_needle = re.escape(needle) # protect any regex metacharacters
pattern = rf'^(?P<before>.*?)(?={esc_needle})' # capture everything before needle
# Compile once – faster for many lines
regex = re.compile(pattern, flags)
# Iterate over lines, keeping a 1‑based line number
matches = (
(ln_no, m.group('before') + ('' if not include_newline else '\n'))
for ln_no, line in enumerate(source.splitlines(True), start=1)
for m in [regex.search(line)]
if m
)
if return_all:
return matches # a generator, you can `list(matches)` later
else:
# Grab the first match, or return None if there is none
return next(matches, None)
2. How it works
Step
Explanation
Regex^(?P<before>.*?)(?=needle)
^ forces the match to start at the beginning of each line (because we use the re.MULTILINE flag). .*? lazily consumes any characters up to the first occurrence of the look‑ahead(?=needle). The captured part is stored in the named group before.
re.MULTILINE
Makes ^ and $ match the start/end of each line, not only the whole string.
Iteration
source.splitlines(True) yields the original lines including line‑breaks (if True). The line number (ln_no) is kept for a helpful context.
return_all
If you need all occurrences, the function yields a generator; otherwise it stops after the first match.
Case‑insensitivity
Controlled via the case_insensitive flag – simply adds re.IGNORECASE.
3. Quick demo
python
doc = """
First line contains nothing.
Second line has the keyword: TARGET and some text before it.
Third line: no target.
Fourth line: beforeTARGET after.
"""
# 1️⃣ Find the first occurrence (case‑sensitive)
result = text_before_substring(doc, "TARGET")
print(result) # → (2, 'Second line has the keyword: ')
# 2️⃣ Find *all* occurrences, case‑insensitive
all_matches = list(text_before_substring(doc,
"TARGET",
case_insensitive=True,
return_all=True))
print(all_matches)
# → [(2, 'Second line has the keyword: '),
# (4, 'Fourth line: before')]
# 3️⃣ If you need the exact slice from the original string (including newline)
first = text_before_substring(doc, "TARGET", include_newline=True)
print(repr(first[1])) # shows the trailing '\n' if present
Output
code
(2, 'Second line has the keyword: ')
[(2, 'Second line has the keyword: '), (4, 'Fourth line: before')]
'Second line has the keyword: \n'
4. One‑liner for the most common case
If you just want the first fragment before a fixed word and don’t need the extra parameters, you can use a tiny helper:
python
def before_one(source: str, needle: str) -> Optional[str]:
pattern = rf'^(.*?)(?={re.escape(needle)})'
m = re.search(pattern, source, flags=re.MULTILINE)
return m.group(1) if m else None
python
>>> before_one("abc needle xyz", "needle")
'abc '
5. What to adapt for your own use
What you might change
How to do it
Different delimiter – e.g., you want everything after* the needle instead of before.
Switch the look‑ahead to a look‑behind: (?<=needle)(.*)$
Ignore leading/trailing whitespace
Wrap the captured group with strip(): m.group('before').strip()
Return only the fragment, not the line number
return m.group('before') instead of (ln_no, ...)
Extract from a file
text = open('myfile.txt', encoding='utf‑8').read(); result = text_before_substring(text, 'myKey')
🎯 TL;DR – Minimal snippet you can copy‑paste
python
import re
def get_before(source: str, needle: str) -> Optional[str]:
# Returns the text before the first occurrence of *needle* on any line
pattern = rf'^(.*?)(?={re.escape(needle)})' # capture everything before needle
m = re.search(pattern, source, flags=re.MULTILINE)
return m.group(1) if m else None
# Example
doc = """alpha
beta TARGET gamma
delta
"""
print(get_before(doc, "TARGET")) # → 'beta '
That’s it – you now have a reusable way to extract the text that appears on the same line before a given substring, only when the substring is present. Happy coding!
SAS – Turn a numeric value into a 14‑character string padded with leading zeros
The most common way is to use the PUT function together with a zero‑filled numeric format (Z14.). Z14. tells SAS to write the number in a field 14 characters wide and to fill any unused positions on the left with zeros.
sas
/*--------------------------------------------------------------
Example data set
--------------------------------------------------------------*/
data have;
input id 8.;
datalines;
1
23
4567
123456789
. /* missing value */
;
run;
/*--------------------------------------------------------------
Convert the numeric ID to a 14‑character text variable
--------------------------------------------------------------*/
data want;
set have;
/* 1) Using the PUT function and the Z14. format */
id_char = put(id, Z14.); /* character variable, length 14 */
/* 2) (optional) make sure the variable really has length 14 */
length id_char $14; /* explicit length – good practice */
/* 3) If you need a character constant without the trailing blanks */
id_char = strip(id_char); /* removes any trailing blanks */
run;
/*--------------------------------------------------------------
Result
--------------------------------------------------------------*/
proc print data=want noobs;
var id id_char;
run;
What you get
id
id_char
1
00000000000001
23
00000000000023
4567
00000000004567
123456789
00000123456789
. (missing)
00000000000000
Why Z14. works
Element
Meaning
Z
“zero‑fill” – left‑pad with zeros
14
total width of the output field (14 chars)
.
decimal point – not needed for integers; you can also use Z14. without a dot for integer values
If you need decimal places you can combine the width and the number of decimals, e.g. Z14.2 (14 total positions, 2 after the decimal).
Alternate approaches
Method
When you might use it
putn(id, 'Z14.')
When the format name is stored in a macro variable or a data‑step variable.
cats('0', put(id, 14.)) then substr(..., length-13)
If you ever need a custom padding character other than 0.
format id Z14.; + put(id, 8.)
When you want SAS to display the padded value automatically (no extra variable).
retain id_char $14; + id_char = put(id, Z14.);
When you want to guarantee the length in a PROC step that otherwise truncates character variables.
Handling missing values
PUT with a numeric format returns a string of zeros for a missing numeric value:
sas
put(. , Z14.) /* → "00000000000000" */
If you prefer a blank or a special token (e.g., "**************"), test for missing first:
sas
if missing(id) then id_char = '**************';
else id_char = put(id, Z14.);
Quick macro for reuse
If you need this conversion in many places, wrap it in a macro: