Here's a Python code that detects if a string contains 'baccalaureat' and either 'releve de notes' or 'releve des notes':
python
def detect_baccalaureat_releve(text):
"""
Detects if the text contains 'baccalaureat' and either 'releve de notes' or 'releve des notes'
Args:
text (str): The text to search in
Returns:
bool: True if both conditions are met, False otherwise
"""
# Convert to lowercase for case-insensitive search
text_lower = text.lower()
# Check for 'baccalaureat'
has_baccalaureat = 'baccalaureat' in text_lower
# Check for either 'releve de notes' or 'releve des notes'
has_releve = 'releve de notes' in text_lower or 'releve des notes' in text_lower
# Return True only if both conditions are met
return has_baccalaureat and has_releve
# Example usage:
if __name__ == "__main__":
# Test cases
test_texts = [
"Voici mon baccalaureat et mon releve de notes",
"Document baccalaureat avec releve des notes",
"Baccalaureat sans releve",
"Releve de notes sans baccalaureat",
"BACCALAUREAT et RELEVE DE NOTES", # Test case sensitivity
"Aucun des mots clés",
"Mon baccalauréat français avec relevé des notes" # Won't match due to accents
]
for i, text in enumerate(test_texts, 1):
result = detect_baccalaureat_releve(text)
print(f"Test {i}: {result} - '{text}'")
Alternative version using regular expressions for more flexible matching:
python
import re
def detect_baccalaureat_releve_regex(text):
"""
Detects if the text contains 'baccalaureat' and either 'releve de notes' or 'releve des notes'
using regular expressions for more flexible matching
Args:
text (str): The text to search in
Returns:
bool: True if both conditions are met, False otherwise
"""
# Case-insensitive patterns
baccalaureat_pattern = r'baccalaur[eé]at' # Handles both 'e' and 'é'
releve_pattern = r'relev[eé]\s+des?\s+notes' # Handles 'de' or 'des' and accents
# Search for patterns
has_baccalaureat = bool(re.search(baccalaureat_pattern, text, re.IGNORECASE))
has_releve = bool(re.search(releve_pattern, text, re.IGNORECASE))
return has_baccalaureat and has_releve
# Example usage with regex version:
if __name__ == "__main__":
test_texts = [
"Voici mon baccalauréat et mon relevé de notes",
"Document baccalaureat avec releve des notes",
"Mon baccalauréat avec relevé des notes",
"BACCALAURÉAT et RELEVÉ DES NOTES"
]
for i, text in enumerate(test_texts, 1):
result = detect_baccalaureat_releve_regex(text)
print(f"Regex Test {i}: {result} - '{text}'")
Simple one-liner version:
python
def check_substrings(text):
text = text.lower()
return 'baccalaureat' in text and ('releve de notes' in text or 'releve des notes' in text)
# Usage
text = "Mon baccalaureat avec releve de notes"
result = check_substrings(text)
print(result) # True
The first version is the most straightforward and handles the exact substrings you specified. The regex version is more flexible and can handle accented characters and variations in spacing. Choose the one that best fits your needs!
In Python, there are several ways to create line breaks without printing the literal \n characters. Here are the main approaches:
1. Using print() with multiple arguments or multiple calls:
python
# Multiple print() calls (each print() adds a newline by default)
print("First line")
print("Second line")
print("Third line")
# Output:
# First line
# Second line
# Third line
2. Using triple quotes for multi-line strings:
python
text = """First line
Second line
Third line"""
print(text)
# Or with variables:
name = "John"
age = 25
message = f"""Hello {name}!
You are {age} years old.
Welcome to our system."""
print(message)
3. Using \n in the string (this creates actual line breaks):
python
print("First line\nSecond line\nThird line")
# Output:
# First line
# Second line
# Third line
4. Using print() with sep and multiple strings:
python
print("First line", "Second line", "Third line", sep="\n")
# Output:
# First line
# Second line
# Third line
5. For your specific baccalaureat detection function:
python
def detect_and_display_results(texts):
for i, text in enumerate(texts, 1):
result = detect_baccalaureat_releve(text)
# Instead of \n, use multiple prints or format nicely
print(f"Test {i}: {result}")
print(f"Text: '{text}'")
print("-" * 50) # Separator line
# Or using triple quotes:
output = f"""Test {i}: {result}
Text: '{text}'
{'-' * 50}"""
print(output)
7. In HTML context (if you're working with web output):
python
# If outputting to HTML
html_output = "First line<br>Second line<br>Third line"
print(html_output)
8. For your original code, here's a cleaner version:
python
def detect_baccalaureat_releve(text):
text_lower = text.lower()
has_baccalaureat = 'baccalaureat' in text_lower
has_releve = 'releve de notes' in text_lower or 'releve des notes' in text_lower
return has_baccalaureat and has_releve
# Clean output without \n
test_texts = [
"Voici mon baccalaureat et mon releve de notes",
"Document baccalaureat avec releve des notes",
"Baccalaureat sans releve"
]
for i, text in enumerate(test_texts, 1):
result = detect_baccalaureat_releve(text)
print(f"Test {i}: {result}")
print(f"Text: '{text}'")
print() # Empty print() for spacing
The key is that \n inside a string creates actual line breaks when printed, while if you want to avoid line breaks entirely, you can use print() with end="" parameter:
python
print("First line", end="")
print("Second line", end="")
print("Third line")
# Output: First lineSecond lineThird line
Here are several ways to extract text that appears before a certain substring on the same line in Python:
1. Basic approach using split():
python
def extract_text_before_substring(text, substring):
"""
Extract text that appears before a substring on the same line
"""
lines = text.split('\n')
results = []
for line in lines:
if substring in line:
# Split the line at the substring and take the part before it
before_text = line.split(substring)[0]
results.append(before_text.strip()) # strip() removes leading/trailing whitespace
return results
# Example usage:
document = """This is line 1
Here is some text before TARGET and after
Another line
More text before TARGET here
No target in this line"""
target = "TARGET"
result = extract_text_before_substring(document, target)
print(result)
# Output: ['Here is some text before ', 'More text before ']
2. Using find() method for more control:
python
def extract_before_substring_find(text, substring):
"""
Extract text before substring using find() method
"""
lines = text.split('\n')
results = []
for line in lines:
pos = line.find(substring)
if pos != -1: # substring found
before_text = line[:pos]
results.append(before_text.strip())
return results
3. Using regular expressions for more advanced matching:
python
import re
def extract_before_substring_regex(text, substring):
"""
Extract text before substring using regex
"""
# Pattern: capture everything from start of line until the substring
pattern = rf'^(.*?){re.escape(substring)}'
lines = text.split('\n')
results = []
for line in lines:
match = re.search(pattern, line)
if match:
before_text = match.group(1)
results.append(before_text.strip())
return results
4. Case-insensitive version:
python
def extract_before_substring_case_insensitive(text, substring):
"""
Extract text before substring (case-insensitive)
"""
lines = text.split('\n')
results = []
substring_lower = substring.lower()
for line in lines:
line_lower = line.lower()
pos = line_lower.find(substring_lower)
if pos != -1:
before_text = line[:pos] # Use original line for correct case
results.append(before_text.strip())
return results
5. Return first occurrence only:
python
def extract_before_first_occurrence(text, substring):
"""
Extract text before the first occurrence of substring
"""
lines = text.split('\n')
for line in lines:
if substring in line:
before_text = line.split(substring)[0]
return before_text.strip()
return None # Return None if substring not found
6. For your baccalaureat example:
python
def extract_before_baccalaureat(document):
"""
Extract text that appears before 'baccalaureat' on the same line
"""
lines = document.split('\n')
results = []
for line in lines:
line_lower = line.lower()
if 'baccalaureat' in line_lower:
# Find position in lowercase, but extract from original line
pos = line_lower.find('baccalaureat')
before_text = line[:pos]
if before_text.strip(): # Only add non-empty results
results.append(before_text.strip())
return results
# Example:
document = """Student name: John Doe baccalaureat mention bien
Date: 2023 baccalaureat scientifique
Some other line
Diplôme: baccalaureat littéraire"""
result = extract_before_baccalaureat(document)
print(result)
# Output: ['Student name: John Doe', 'Date: 2023', 'Diplôme:']
7. More flexible version with multiple substrings:
python
def extract_before_any_substring(text, substrings):
"""
Extract text before any of the given substrings
"""
lines = text.split('\n')
results = []
for line in lines:
line_lower = line.lower()
for substring in substrings:
substring_lower = substring.lower()
if substring_lower in line_lower:
pos = line_lower.find(substring_lower)
before_text = line[:pos]
if before_text.strip():
results.append({
'before_text': before_text.strip(),
'found_substring': substring,
'full_line': line
})
break # Stop after first match in this line
return results
# Example:
document = """Name: John baccalaureat
Grade: A+ releve de notes
Score: 85 releve des notes"""
substrings = ['baccalaureat', 'releve de notes', 'releve des notes']
result = extract_before_any_substring(document, substrings)
for item in result:
print(f"Before '{item['found_substring']}': '{item['before_text']}'")
8. Simple one-liner for single use:
python
# Quick one-liner
text = "Some text before TARGET and after"
before_target = text.split("TARGET")[0] if "TARGET" in text else ""
print(before_target) # "Some text before "
Choose the approach that best fits your needs. The basic split() method is usually sufficient for simple cases, while regex provides more flexibility for complex pattern matching.
In SAS, you can transform a number into a 14-position text with leading zeros using the PUT function with the Z format. Here are several ways to do this:
1. Using the Z format (most common method):
sas
data example;
number = 12345;
/* Transform number to 14-position text with leading zeros */
text_with_zeros = put(number, z14.);
put number= text_with_zeros=;
run;
/* Output: number=12345 text_with_zeros=00000000012345 */
2. Alternative using BEST format with leading zeros:
sas
data example;
number = 12345;
/* Using z14. format */
text_14_pos = put(number, z14.);
/* For different numbers */
num1 = 123;
num2 = 9876543;
num3 = 0;
text1 = put(num1, z14.);
text2 = put(num2, z14.);
text3 = put(num3, z14.);
put num1= text1=;
put num2= text2=;
put num3= text3=;
run;
/* Output:
num1=123 text1=00000000000123
num2=9876543 text2=00000009876543
num3=0 text3=00000000000000
*/
3. In a DATA step with multiple variables:
sas
data transform_numbers;
input original_number;
/* Transform to 14-position text with leading zeros */
formatted_text = put(original_number, z14.);
datalines;
12345
987
1234567890
0
999999999999
;
run;
proc print data=transform_numbers;
run;
4. Using in PROC SQL:
sas
proc sql;
select
original_number,
put(original_number, z14.) as formatted_text
from (
select 12345 as original_number union all
select 987 union all
select 1234567890 union all
select 0
);
quit;
5. Creating a format for reuse:
sas
/* Create a custom format */
proc format;
picture z14fmt
low-high = '00000000000009'
(prefix='');
run;
data example;
number = 12345;
/* Using custom format */
text_custom = put(number, z14fmt14.);
/* Using standard z format */
text_standard = put(number, z14.);
put number= text_custom= text_standard=;
run;
6. For handling negative numbers:
sas
data handle_negatives;
input number;
/* Standard z14 format */
text_z14 = put(number, z14.);
/* For negative numbers, you might want special handling */
if number < 0 then
text_custom = '-' || put(abs(number), z13.);
else
text_custom = put(number, z14.);
datalines;
12345
-12345
0
987654321
-987654321
;
run;
proc print data=handle_negatives;
run;
7. Using in a macro:
sas
%macro num_to_text14(input_var, output_var);
&output_var = put(&input_var, z14.);
%mend;
data example_macro;
number = 12345;
%num_to_text14(number, formatted_number);
put number= formatted_number=;
run;
Key Points:
Z14. format: Creates a 14-character string with leading zeros
PUT function: Converts numeric to character using specified format
The result is always exactly 14 characters long
If the number has more than 14 digits, it may be truncated or display as asterisks
Negative numbers will include the minus sign in the 14 positions
Common variations:
sas
data variations;
number = 12345;
/* Different lengths */
text_10 = put(number, z10.); /* 0000012345 */
text_8 = put(number, z8.); /* 00012345 */
text_6 = put(number, z6.); /* 012345 */
put number= text_10= text_8= text_6=;
run;
The Z14. format is the most straightforward and commonly used method for this transformation in SAS.