- Python script to map one string to another string
- 1 Answer 1
- Python map Function Explanation and Examples
- Syntax of Python map function
- Parameters of Python map function
- First argument: A function
- Second argument: An iterable
- Examples: Python map() with string
- Python map() with tuple
- Python map() with list
- Example: Python map() function with lambda function
- Example: Passing multiple arguments to map() function in Python
- Conclusion
- Python map() function
- Python map() function
- Python map() example
- Python map() with string
- Python map() with tuple
- Python map() with list
- Converting map to list, tuple, set
- Python map() with lambda
- Python map() multiple arguments
- Python map() with function None
Python script to map one string to another string
I have a file called file1.txt whose contents are like: file1.txt Python is a general-purpose, interpreted, interactive, object-oriented and high-level programming language. Python was developed by Guido van Rossum in the late eighties and early nineties at the National Research Institute for Mathematics and Computer Science in the Netherlands. Python is derived from many other languages, including ABC, Modula-3, C, C++, Algol-68, SmallTalk and Unix shell and other scripting languages. Python is copyrighted. Like Perl, Python source code is now available under the GNU General Public License (GPL). I want to map a string for eg. the third sentence in the file to another string like -«Python was designed to be highly readable which uses English keywords frequently » . How this mapping can be done in python? I got to know that dictionary is equivalent to hashmap in python but can dictionary be used to map 1 string to another?? I tried something like:
f=open("log5.txt") dict = print(f.readline()) print(dict['f.readline()'])
But the above program maps the first sentence and also is there any better and efficient way to write the above program.
1 Answer 1
Alright, 2 easy solutions: .split(. ) and re.(. )
text = "Python is . License (GPL)." # add back the periods, this isn't the most efficient way (use regex or a tokenizer for better results but this works) def add_periods(sentences) return [sentence + "." for sentence in periodless_sentences] # i have no idea why you'd want to do this def map_to_sentence_index(sentences): return # split periodless_sentences = str.split('. ') # regex import re sentences = re.split(r' *[\.\?!][\'"\)\]]* *', text)
In python map means map(func, lst) where func is some function you want to apply to every element of lst . This is not what you are describing. map is a reserved keyword.
Honestly your question makes very little sense in the context of python and looks to be copy-pasted from a textbook. Please don’t use stackoverflow as a homework solutions site. That said, here’s the solution lol
Python map Function Explanation and Examples
The purpose of the Python map function is to apply the same procedure to every item in an iterable data structure. Iterable data structures can include lists, generators, strings, etc. In a very basic example, the map can iterate over every item in a list and apply a function to each item.
Python borrows the concept of the map from the functional programming domain. It is an inbuilt function that is used to apply the function on all the elements of specified iterable and return map objects. the map can also be used in situations like calling a particular method on all objects stored in a list which change the state of the object.
Syntax of Python map function
Python map() function syntax is:
Parameters of Python map function
function : It is a function to which map passes each element of given iterable. iterable : It is a iterable which is to be mapped.
NOTE: You can pass one or more iterable to the map() function.
We can pass multiple iterable arguments to map() function, in that case, the specified function must have that many arguments. The function will be applied to these iterable elements in parallel. With multiple iterable arguments, the map iterator stops when the shortest iterable is exhausted.
First argument: A function
The map function accepts a function as the first argument. When we think about a function in Python, we automatically think about the def keyword, but the map function does not only accept functions created by the user using def keyword but also built-in and anonymous functions, and even methods.
Second argument: An iterable
When we think about an iterable We automatically think about lists, but iterables are much more than lists. An iterable is an object with a countable number of values that can be iterated for example using a for loop, Sets, tuples, dictionaries are iterables as well, and they can be used as the second argument of the map function.
Examples: Python map() with string
def to_upper_case(s): return str(s).upper()
It’s a simple function that returns the upper case string representation of the input object.
I am also defining a utility function to print iterator elements. The function will print iterator elements with white space and will be reused in all the code snippets.
def print_iterator(it): for x in it: print(x, end=' ') print('') # for new line
Let’s look at the map() function example with different types of iterables.
# map() with string map_iterator = map(to_upper_case, 'abc') print(type(map_iterator)) print_iterator(map_iterator)
Python map() with tuple
# map() with tuple map_iterator = map(to_upper_case, (1, 'a', 'abc')) print_iterator(map_iterator)
Python map() with list
map_iterator = map(to_upper_case, ['x', 'a', 'abc']) print_iterator(map_iterator)
Example: Python map() function with lambda function
In the map() function along with iterable sequence, we can also the lambda function. Let’s use a lambda function to reverse each string in the list as we did above using a global function, Python
listOfStr = ['hi', 'this' , 'is', 'a', 'very', 'simple', 'string' , 'for', 'us'] # Reverse each string in the list using lambda function & map() modifiedList = list(map(lambda x : x[::-1], listOfStr)) print('Modified List : ', modifiedList)
Modified List : ['ih', 'siht', 'si', 'a', 'yrev', 'elpmis', 'gnirts', 'rof', 'su']
It iterates over the list of string and applies lambda function on each string element. Then stores the value returned by lambda function to a new sequence for each element. Then in last returns the new sequence of reversed string elements.
Example: Passing multiple arguments to map() function in Python
The map() function, along with a function as an argument can also pass multiple sequences like lists as arguments. Let’s see how to pass 2 lists in
map() function and get a joined list based on them.
Suppose we have two lists i.e.
list1 = ['hi', 'this', 'is', 'a', 'very', 'simple', 'string', 'for', 'us'] list2 = [11,22,33,44,55,66,77,88,99]
Now we want to join elements from list1 to list2 and create a new list of the same size from these joined lists i.e. new lists should be like this,
['hi_11', 'this_22', 'is_33', 'a_44', 'very_55', 'simple_66', 'string_77', 'for_88', 'us_99']
Conclusion
- The map function has two arguments (1) a function, and (2) an iterable.
- Applies the function to each element of the iterable and returns a map object.
- The returned map object can be easily converted in another iterable using built-in functions.
If you didn’t find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.
Python map() function
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
Python map() function is used to apply a function on all the elements of specified iterable and return map object. Python map object is an iterator, so we can iterate over its elements. We can also convert map object to sequence objects such as list, tuple etc. using their factory functions.
Python map() function
We can pass multiple iterable arguments to map() function, in that case, the specified function must have that many arguments. The function will be applied to these iterable elements in parallel. With multiple iterable arguments, the map iterator stops when the shortest iterable is exhausted.
Python map() example
def to_upper_case(s): return str(s).upper()
It’s a simple function that returns the upper case string representation of the input object. I am also defining a utility function to print iterator elements. The function will print iterator elements with white space and will be reused in all the code snippets.
def print_iterator(it): for x in it: print(x, end=' ') print('') # for new line
Python map() with string
# map() with string map_iterator = map(to_upper_case, 'abc') print(type(map_iterator)) print_iterator(map_iterator)
Python map() with tuple
# map() with tuple map_iterator = map(to_upper_case, (1, 'a', 'abc')) print_iterator(map_iterator)
Python map() with list
map_iterator = map(to_upper_case, ['x', 'a', 'abc']) print_iterator(map_iterator)
Converting map to list, tuple, set
Since map object is an iterator, we can pass it as an argument to the factory methods for creating a list, tuple, set etc.
map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_list = list(map_iterator) print(my_list) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_set = set(map_iterator) print(my_set) map_iterator = map(to_upper_case, ['a', 'b', 'c']) my_tuple = tuple(map_iterator) print(my_tuple)
Python map() with lambda
We can use lambda functions with map() if we don’t want to reuse it. This is useful when our function is small and we don’t want to define a new function.
list_numbers = [1, 2, 3, 4] map_iterator = map(lambda x: x * 2, list_numbers) print_iterator(map_iterator)
Python map() multiple arguments
# map() with multiple iterable arguments list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8) map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers) print_iterator(map_iterator)
Output: 5 12 21 32 Notice that our function has two arguments. The output map iterator is the result of applying this function to the two iterable elements in parallel. Let’s see what happens when the iterables are of different sizes.
# map() with multiple iterable arguments of different sizes list_numbers = [1, 2, 3, 4] tuple_numbers = (5, 6, 7, 8, 9, 10) map_iterator = map(lambda x, y: x * y, list_numbers, tuple_numbers) print_iterator(map_iterator) map_iterator = map(lambda x, y: x * y, tuple_numbers, list_numbers) print_iterator(map_iterator)
So when the arguments are of different sizes, then the map function is applied to the elements until one of them is exhausted.
Python map() with function None
map_iterator = map(None, 'abc') print(map_iterator) for x in map_iterator: print(x)
Traceback (most recent call last): File "/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples/python_map_example.py", line 3, in for x in map_iterator: TypeError: 'NoneType' object is not callable
You can checkout complete python script and more Python examples from our GitHub Repository. Reference: Official Documentation
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us