accy570lab_week11
.html
keyboard_arrow_up
School
University of Illinois, Urbana Champaign *
*We aren’t endorsed by this school
Course
570
Subject
Computer Science
Date
Dec 6, 2023
Type
html
Pages
5
Uploaded by HighnessLoris3604
Week 11 Lab
¶
Python Regular Expression
¶
A regex is a sequence of characters that defines a search pattern, used mainly for
performing find and replace operations in search engines and text processors.
In [1]:
import re
Raw Strings
¶
Different functions in Python's re module use raw string as an argument. A normal
string, when prefixed with 'r' or 'R' becomes a raw string.
The difference between a normal string and a raw string is that the normal string in
print() function translates escape characters (such as \n, \t etc.) if any, while those in a
raw string are not.
In [2]:
print('Hello\nWorld')
Hello
World
In [3]:
print(r'Hello\nWorld')
Hello\nWorld
In [4]:
'\d'
Out[4]:
'\\d'
Meta Characters
¶
Some characters carry a special meaning when they appear as a part pattern
matching string.
. ^ $ * + ? [ ] \ | ( ) { }
Pattern
Description
\d
Matches any decimal digit; this is equivalent to the class [0-
9]
\D
Matches any non-digit character
\s
Matches any whitespace character
\S
Matches any non-whitespace character
\w
Matches any alphanumeric character
\W
Matches any non-alphanumeric character
\b
Boundary that's not \w
.
Matches with any single character except newline ‘\n'
?
match 0 or 1 occurrence of the pattern to its left
Pattern
Description
+
1 or more occurrences of the pattern to its left
*
0 or more occurrences of the pattern to its left
[...]
Matches any single character in a square bracket
{n,m}
Matches at least n and at most m occurrences of preceding
a|b
Matches a or b
re.findall(pattern, string)
¶
Searches for all occurance of the pattern and returns a list of all occurrences.
In [5]:
s = "We watched Star Wars on Wednesday night at 8:30."
In [6]:
re.findall(r'.', s)
Out[6]:
['W',
'e',
' ',
'w',
'a',
't',
'c',
'h',
'e',
'd',
' ',
'S',
't',
'a',
'r',
' ',
'W',
'a',
'r',
's',
' ',
'o',
'n',
' ',
'W',
'e',
'd',
'n',
'e',
's',
'd',
'a',
'y',
' ',
'n',
'i',
'g',
'h',
't',
' ',
'a',
't',
' ',
'8',
':',
'3',
'0',
'.']
In [7]:
re.findall(r'.*', s)
Out[7]:
['We watched Star Wars on Wednesday night at 8:30.', '']
In [8]:
re.findall(r'.+', s)
Out[8]:
['We watched Star Wars on Wednesday night at 8:30.']
In [9]:
re.findall(r'\w+', s)
Out[9]:
['We', 'watched', 'Star', 'Wars', 'on', 'Wednesday', 'night', 'at', '8', '30']
In [10]:
re.findall(r'[a-zA-Z0-9]+', s)
Out[10]:
['We', 'watched', 'Star', 'Wars', 'on', 'Wednesday', 'night', 'at', '8', '30']
In [11]:
re.findall(r'\d+', s)
Out[11]:
['8', '30']
In [12]:
re.findall(r'[0-9]+', s)
Out[12]:
['8', '30']
In [13]:
re.findall(r'[Ww]\w+', s)
Out[13]:
['We', 'watched', 'Wars', 'Wednesday']
Exercise 1
Find all words start with a capital letter in s.
In [9]:
s
Out[9]:
'We watched Star Wars on Wednesday night at 8:30.'
Your preview ends here
Eager to read complete document? Join bartleby learn and gain access to the full version
- Access to all documents
- Unlimited textbook solutions
- 24/7 expert homework help
Related Questions
3. String
(a)
Write a Python function that accepts a string s and an integer n with a single
digit (i.e., 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9) as its arguments, and returns a new string that
replaces every digit n found in s by a new digit that equals to (n + 1) %10. The function
returns an empty string if n is not a single digit integer or is negative.
COMP132 Assignment #2
replace_string("He330", 3)-> "He440"
"He331"
replace_string("He330",0)->
replace_string("He330",-4)
replace_string("He330",
->
12)->
11 11
11 11
(b)
Write a Python function that accepts a string as the argument, moves the first
3 characters of the string to the end, and prints it out. If the length of the string is less than
3, your function should print an error message.
move_string ("Hello") ->loHel
move_string ("Hi, My name is Mark.") -> My name is Mark. Hi,
move_string ("Hi")->Invalid String
arrow_forward
Write a function that returns a binary string from an octal number. The function header is as follows:
string octal2Binary(const int& octalNumber)
Write a test program that prompts the user to enter an octal number, uses octal- 2Binary function to parse it into an equivalent binary string and displays the binary string.
arrow_forward
Binary to String
To translate the binary data, convert the binary information into ASCII characters. Create the function binary_to_ascii_string() that accepts a list of binaries, binary_values, and returns them as a string.
As an example, the list [‘01000001’, ‘01101100’, ‘01100101’, ‘01111000’] will return the string ‘Alex’ and the list [‘01100100’, ‘01110101, ‘01100100’, 01110101] will return the string ‘dudu’.
arrow_forward
Match the std::string constructor on right to its function on left.
Source:
https://cplusplus.com/reference/string/string/string/ E
string()
string (const string& str)
string (const char* s)
string (size_t n, char c)
[Choose]
[Choose ]
constructs a copy of str.
constructs an empty string, with a length of zero characters.
copies the null-terminated character sequence (C-string) pointed by s.
fills the string with n consecutive copies of character c.
[Choose ]
arrow_forward
PYTHON
Problem Statement
Implement a function which takes two arguments: the first is a string and the second is a single character (as a string). This function should move every instance of the given character in the string to the end of the string, and then return (do NOT print) the final string.
NOTE: Only write code within the function. You do not need to utilize the "input()" function. The autograder passes inputs directly to the function as arguments, and the checked output is the returned value from the function.
Sample Input
"hello how are you?", "o"
Sample Output
"hell hw are yu?ooo"
Starter Code
def move_character(word, character):
arrow_forward
Binary to String
Create a function binary_to_ascii_string() that converts binary information into ASCII characters. This accepts a list of binaries, binary_values, and returns them as a string. (Note that the binary strings have 8 characters.)
An example is present in the photo below. Thank you!
arrow_forward
【Python Programming】Writing a game is _word_drome(), a Chinese string palindrome that determines whether the content is given, all non-English words are loaded, and the Chinese string is required to be read from the file.
arrow_forward
Python program question
arrow_forward
Launch Meeting - Zoc X
S Launch Meeting Zoc X
Is Everyone Really Equ x
E Reading Response 6
OCh7: Oppression & Se x
SThank you for downlc X
s.ucsc.edu/courses/46018/assignments/294537
2. are_anagrams
This function takes two strings and returns True if they are anagrams of one another, which is to say that they contain
the same letters, possibly rearranged, ignoring spaces and case. You can assume that the two input strings contain only
letters and spaces.
Sample calls should look like this:
>>> are_anagrams ("bimmy is my friend", "My Bird Fey Minims")
True
>>> are_anagrams ("bimmy is my friend", "hello everyone")
False
>>> are_anagrams ("internet anagram server", "I rearrangement servant")
True
>>> are_anagrams ("internet anagram server", "internet anagram server")
True
3. find_movies_by_director
4:11 PM
This function takes a list of tuples (representing movies) and a string (representing a name of a director) and returns a
65°F Sunny
11/2/2021
e search
arrow_forward
Character Count
Code in C language
arrow_forward
INSTRUCTIONS: Write a Python script/code to do the given problems.
EMOTIFY PROBLEM: Create a function that takes a string and returns a string with its
letters in alphabetical order.
Example:
alphabet_soup(“hello")
- ehllo
alphabet_soup(“hacker") – acehkr
arrow_forward
remove_substring_from_string(s, substr): This function takes two strings s and substr as input.
It creates a new string from the original string s by removing all instances, if any, of the string
substr, and then returns the new string.
>>> remove_substring_from_string("Python is best language except for C++.
except for C++")
'Python is best language. '
arrow_forward
Computer Science
C++
Write a program that:
Gets a character array (C-string) using cin.get to allow blanks in the C-string
Prints the C-string (what they input)
Prints the length (number of characters) in the C-string
arrow_forward
// write a function that takes the input string and reverses it// example// argument: Hello// return: olleHfunction reverseThisString(string){
}
// write a function that takes the input string and switches all uppercase characters to lowercase and lowercase charcaters to uppercase// example:// argument: Hello World// return: hELLO wORLDfunction swapCase(string) {
}
//convert array of numbers from farenheit to celcius// example:// argument: [23, 32, 41, 50, 59]// return: [-5, 0, 5, 10, 15]// hint: use Array.mapfunction toCelcius(array){
}
//write a function that takes an input array and returns an array of booleans (>=75) or fail (<75)// example:// argument: [20, 30, 50, 80, 90, 100]// return: [false, false, false, true, true, true]// hint: use Array.mapfunction passOrFail(array){
}
//write code that loops through the two variables returns an array ['2 is zwei', '3 is drei', '4 is vier', '5 is fünf', '6 is sechs']// example:// return: ['2 is zwei', '3 is drei', '4 is vier', '5 is…
arrow_forward
Python language
Please don't use in loops
arrow_forward
In C programming language
Question (Strings)
Write a function find_Substring() that finds a substring into a string. Pass array s1 and s2 to this function and prints if the substring is present or not.
Expected Output 1:
Enter string
This is a javascript Enter substring script
The substring is present
Expected Output 2:
Enter string
This is a javascript
Enter substring
Jscript
The substring is not present
arrow_forward
///-In python-///
def get_words_last_1():"""The function should take a list of wordsas an input parameter and return a new list of stringswith the last character removed. (Use string slicing)If the word is empty or has only 1 character, then skip it.""" pass
The code should aslo have if __name__ == "__main__" section.
arrow_forward
Programming language c++
arrow_forward
/// in python ///
def get_words_last_1():"""The function should take a list of wordsas an input parameter and return a new list of stringswith the last character removed. (Use string slicing)If the word is empty or has only 1 character, then skip it.""" pass
arrow_forward
Part 3
plase skip it if you dont know the correct answer i need it urgent. Will doewnvote in case of wrong or copied answers from chegg or bartleby!
A regular expression (shortened as regex or regexp; also referred to as rational expression) is a sequence of characters that specifies a search pattern. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
using regex create a python program to verify the string having each word start from 'f'? It should return True otherwise false.
arrow_forward
longest.py -> using sys.argv
● Create a program, longest.py, that has a function that takes one string argument and prints a sentence indicating the longest word in that string.
If there is more than one word print only the first. Your print statement should read: “The longest word is x” Where x = the longest word. The word should be all lowercase.
arrow_forward
Python Pgogram
Write a program that incorporates an algorithm with a function that will check whether or not a string is in a valid password format with the following rules:
A password must have at least ten characters.A password consists of only letters, digits and symbol(s).A password must contain at least two digits.
A password must contain at least one uppercase letter
A password must contain at least one special symbol
Your program should continue to prompt until the user enters a valid password.
Regular expressions (regex) are not allowed!
arrow_forward
7. The following function converts a postfix expression to an infix expression assuming the
expression can only contain unsigned integer numbers and +' and -' operators.
1. public static String convert (String postfix) {
2.
String operand1, operand2, infix;
3.
Stack s = new AStack;
4.
int i = 0;
5.
while (i < postfix.length) {
char nextc = postfix.charAt (i);
if ((nextc
6.
7.
'+')|| (nextc == '-') {
==
operand2 = s.pop (); operandl = s.pop () ;
infix = '(' + operandl + nextc + operand2 + ')';
s.push (infix); i++;
8.
9.
10.
11.
}
12.
else if (Character.isDigit (nextc)){
int start = i;
while (Character.isDigit (postfix.charAt (i)) i++;
infix = postfix.substring (start, i);
s.push (infix);
13.
14.
15.
16.
17.
}
else i++;
18.
19.
}
20
return s.pop () ;
21. }
(a) Rewrite only the lines of code that need to be changed so that the above function converts a
postfix expression to a prefix expression.
(b) Describe in words what changes are needed on the above given convert () function so that it…
arrow_forward
Implement the following function:
Code should be written in python.
arrow_forward
USING ARROW FUNCTIONS IN JAVASCRIPT WRITE THE FOLLOWING CODE
arrow_forward
Linux !#bin/bash
NOT JAVA OR C++. I NEED LINUX SCRIPT
Word Separator Write a program that accepts as input a sentence in which all of the words are run together but the first character of each word is uppercase. Convert the sentence to a string in which the words are separated by spaces and only the first word starts with an uppercase letter. For example the string “StopAndSmellTheRoses.” would be converted to “Stop and smell the roses.”
arrow_forward
SEE MORE QUESTIONS
Recommended textbooks for you
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT
Related Questions
- 3. String (a) Write a Python function that accepts a string s and an integer n with a single digit (i.e., 0, 1, 2, 3, 4, 5, 6, 7, 8, or 9) as its arguments, and returns a new string that replaces every digit n found in s by a new digit that equals to (n + 1) %10. The function returns an empty string if n is not a single digit integer or is negative. COMP132 Assignment #2 replace_string("He330", 3)-> "He440" "He331" replace_string("He330",0)-> replace_string("He330",-4) replace_string("He330", -> 12)-> 11 11 11 11 (b) Write a Python function that accepts a string as the argument, moves the first 3 characters of the string to the end, and prints it out. If the length of the string is less than 3, your function should print an error message. move_string ("Hello") ->loHel move_string ("Hi, My name is Mark.") -> My name is Mark. Hi, move_string ("Hi")->Invalid Stringarrow_forwardWrite a function that returns a binary string from an octal number. The function header is as follows: string octal2Binary(const int& octalNumber) Write a test program that prompts the user to enter an octal number, uses octal- 2Binary function to parse it into an equivalent binary string and displays the binary string.arrow_forwardBinary to String To translate the binary data, convert the binary information into ASCII characters. Create the function binary_to_ascii_string() that accepts a list of binaries, binary_values, and returns them as a string. As an example, the list [‘01000001’, ‘01101100’, ‘01100101’, ‘01111000’] will return the string ‘Alex’ and the list [‘01100100’, ‘01110101, ‘01100100’, 01110101] will return the string ‘dudu’.arrow_forward
- Match the std::string constructor on right to its function on left. Source: https://cplusplus.com/reference/string/string/string/ E string() string (const string& str) string (const char* s) string (size_t n, char c) [Choose] [Choose ] constructs a copy of str. constructs an empty string, with a length of zero characters. copies the null-terminated character sequence (C-string) pointed by s. fills the string with n consecutive copies of character c. [Choose ]arrow_forwardPYTHON Problem Statement Implement a function which takes two arguments: the first is a string and the second is a single character (as a string). This function should move every instance of the given character in the string to the end of the string, and then return (do NOT print) the final string. NOTE: Only write code within the function. You do not need to utilize the "input()" function. The autograder passes inputs directly to the function as arguments, and the checked output is the returned value from the function. Sample Input "hello how are you?", "o" Sample Output "hell hw are yu?ooo" Starter Code def move_character(word, character):arrow_forwardBinary to String Create a function binary_to_ascii_string() that converts binary information into ASCII characters. This accepts a list of binaries, binary_values, and returns them as a string. (Note that the binary strings have 8 characters.) An example is present in the photo below. Thank you!arrow_forward
- 【Python Programming】Writing a game is _word_drome(), a Chinese string palindrome that determines whether the content is given, all non-English words are loaded, and the Chinese string is required to be read from the file.arrow_forwardPython program questionarrow_forwardLaunch Meeting - Zoc X S Launch Meeting Zoc X Is Everyone Really Equ x E Reading Response 6 OCh7: Oppression & Se x SThank you for downlc X s.ucsc.edu/courses/46018/assignments/294537 2. are_anagrams This function takes two strings and returns True if they are anagrams of one another, which is to say that they contain the same letters, possibly rearranged, ignoring spaces and case. You can assume that the two input strings contain only letters and spaces. Sample calls should look like this: >>> are_anagrams ("bimmy is my friend", "My Bird Fey Minims") True >>> are_anagrams ("bimmy is my friend", "hello everyone") False >>> are_anagrams ("internet anagram server", "I rearrangement servant") True >>> are_anagrams ("internet anagram server", "internet anagram server") True 3. find_movies_by_director 4:11 PM This function takes a list of tuples (representing movies) and a string (representing a name of a director) and returns a 65°F Sunny 11/2/2021 e searcharrow_forward
- Character Count Code in C languagearrow_forwardINSTRUCTIONS: Write a Python script/code to do the given problems. EMOTIFY PROBLEM: Create a function that takes a string and returns a string with its letters in alphabetical order. Example: alphabet_soup(“hello") - ehllo alphabet_soup(“hacker") – acehkrarrow_forwardremove_substring_from_string(s, substr): This function takes two strings s and substr as input. It creates a new string from the original string s by removing all instances, if any, of the string substr, and then returns the new string. >>> remove_substring_from_string("Python is best language except for C++. except for C++") 'Python is best language. 'arrow_forward
arrow_back_ios
SEE MORE QUESTIONS
arrow_forward_ios
Recommended textbooks for you
- C++ Programming: From Problem Analysis to Program...Computer ScienceISBN:9781337102087Author:D. S. MalikPublisher:Cengage LearningEBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT
C++ Programming: From Problem Analysis to Program...
Computer Science
ISBN:9781337102087
Author:D. S. Malik
Publisher:Cengage Learning
EBK JAVA PROGRAMMING
Computer Science
ISBN:9781337671385
Author:FARRELL
Publisher:CENGAGE LEARNING - CONSIGNMENT