Python String – Java2Blog https://java2blog.com A blog on Java, Python and C++ programming languages Sat, 25 Nov 2023 05:29:13 +0000 en-US hourly 1 https://wordpress.org/?v=6.2.9 https://java2blog.com/wp-content/webpc-passthru.php?src=https://java2blog.com/wp-content/uploads/2022/09/cropped-ICON_LOGO_TRANSPARENT-32x32.png&nocache=1 Python String – Java2Blog https://java2blog.com 32 32 Add Spaces Between Characters in Python https://java2blog.com/add-spaces-between-characters-python/?utm_source=rss&utm_medium=rss&utm_campaign=add-spaces-between-characters-python https://java2blog.com/add-spaces-between-characters-python/#respond Thu, 27 Oct 2022 17:49:34 +0000 https://java2blog.com/?p=20942 A string is the generic data type that is offered by Python to store and represent a series of Unicode characters. There might be a need to add a space between all characters of a given string. This tutorial focuses on and demonstrates the different ways available to add spaces between characters in Python.

The first part of the article focuses on how to add spaces between characters in Python while the latter half provides the solution on how to add spaces between numbers and characters in a string in Python.

How To Add Spaces Between Characters in Python?

There are several ways to add spaces between characters in Python, ranging from making use of the in-built join() function to iterating with the help of a for loop to importing an external library and utilizing its functions, all of which have been described in this article below.

Using the join() function

The str.join() function returns a new string that contains the concatenation of the strings given as the iterable.

When the join() function is called on an empty string that contains solely a space, while the specified string to be worked on is passed as an argument to the function, then, the task to add spaces between characters in Python can be successfully implemented.

The following code uses the join() function to add spaces between characters in Python.

x = "Java2blog"
y = ' '.join(x)
print(y)

Output:

J a v a 2 b l o g

Using a for loop

A simple for loop can be utilized to iterate through the given string and manually add a space between all the characters of the string in Python.

The following code uses a for loop to add spaces between characters in Python.

x = "Java2blog"
y = ' '
for i in x:
   y = y + i + ' '
print(y)

Output:

J a v a 2 b l o g

We should note that there may be a leading space in the output string as the for loop starts adding a space before the first character as well when the loop is run.

Using the strip() function along with a for loop

A little tweak in the above program and the addition of the strip() function make up for another approach that can successfully implement the task of adding spaces between characters in Python.

The strip() function can be utilized to get rid of any characters from the beginning or the end of a given string. In our case, we basically utilize the strip() function to truncate or remove any leading or trailing spaces that are a hindrance to the result that we need.

The following code uses the strip() function along with a for loop to add spaces between characters in Python.

x = "Java2blog"
y = ' '
for i in x:
    y += i + ' ' * 1
y = y.strip()
print(repr(y))

Output:

‘J a v a 2 b l o g’

Using the replace() function

The replace() function in Python, as its name suggests, is utilized to replace a given phrase with another phrase, both of which are specified by the programmer and are passed as arguments to the function.

The following code uses the replace() function to add spaces between characters in Python.

x = "Java2blog"
def spacingez(x):
    return x.replace('',' ')[1:-1]
print(spacingez(x))

Output:

J a v a 2 b l o g

How To Add Spaces Between Number and Character in Python?

We may encounter a string that contains both numbers as well as letters from the English alphabet. In those cases, there must be a need to add a space between the number and the character. This part of the article aims to provide the different approaches available to implement this task of adding spaces between a number and a character in Python.

Using the replace() function along with a nested for loop

The replace() function comes in handy in the implementation of this task as well. Apart from the replace() function, we also need a nested for loop to iterate through the strings and specify certain conditions that need to be pertained to in order to achieve an accurate result.

The following code uses the replace() function along with a nested for loop to add spaces between a number and a character in Python.

x = 'Java2blog'
n="0123456789"
for i in x:
    if i in n:
        x=x.replace(i," "+i+" ")
y=x
print(str(y))

Output:

Java 2 blog

Using the re.sub() function

The re.sub() function is a part of the regex module, which needs to be imported to the Python code in order to utilize this function. The regex module is an abbreviation for Regular Expression and provides several functions to manipulate and deal with the same.

The re.sub() function takes an occurrence of a specified sub-string and replaces it with another sub-string. Here, we segregate the given string by targeting the numbers rather than the letters of the English Alphabet.

The following code uses the re.sub() function to add spaces between a number and a character in Python.

import re
x = 'Java2blog'
y = re.sub('(\d+(\.\d+)?)', r' \1 ', x)
print(str(y))

Output:

Java 2 blog

Using a lambda function along with the regex module

A lambda function can be defined as an anonymous function that is capable of having just one expression while taking in as many arguments as the user wants.

The re.sub() function is utilized along with the lambda function here to implement the task at hand successfully.

The following code uses a lambda function along with the regex module to add spaces between a number and a character in Python.

import re
x = 'Java2blog'
y = re.sub("[A-Za-z]+", lambda ele: " " + ele[0] + " ", x)
print(str(y))

Output:

Java 2 blog

That’s all how to add spaces between characters in Python.

]]>
https://java2blog.com/add-spaces-between-characters-python/feed/ 0
Convert Hex to String in Python https://java2blog.com/python-hex-to-string/?utm_source=rss&utm_medium=rss&utm_campaign=python-hex-to-string https://java2blog.com/python-hex-to-string/#respond Fri, 14 Apr 2023 19:11:57 +0000 https://java2blog.com/?p=23368 1. Introduction

The representation of data in Hexadecimal is commonly used in computer programming. It is used to represent binary data in a human-readable form, as understanding the machine language (i.e., Binary) is difficult for humans. Hexadecimal notation is used in networking protocols, e.g., IPv6 and cryptography, and widely used in graphics, e.g. to represent numbers. Note that hexadecimal uses 16 digits, including 0-9 and A-F, to represent numbers.

Considering the importance of hexadecimal, some programming languages and APIs require string representation of binary data. As a lot of data is in hexadecimal form, so we need to convert the hexadecimal number to a string. This conversion helps to display and manipulate the binary data as text, which makes the task more convenient for humans.

In python language, there are different ways to convert Hex to String.

Method 1: Using bytes.fromhex() method

byte_str = bytes.fromhex(hex_str)            #Convert hex string to bytes
regular_str = byte_str.decode('utf-8')       #Convert bytes to regular string

Method 2: Using binascii module

byte_str = binascii.unhexlify(hex_str)           # Convert hex string to bytes
regular_str = byte_str.decode('utf-8')           # Convert bytes to regular string

Method 3: Using codecs module

byte_str = binascii.unhexlify(hex_str)           # Convert hex string to bytes
regular_str = byte_str.decode('utf-8')           # Convert bytes to regular string

Method 4: Using List comprehension

regular_str = ''.join([chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2)])

Let’s go through each method in detail.

2. Using bytes.fromhex() Method

Use the bytes.fromhex() method to convert a hexadecimal string to a simple string in Python.

hex_str = "48656c6c6f20576f726c64"           #Hex string
byte_str = bytes.fromhex(hex_str)            #Convert hex string to bytes
regular_str = byte_str.decode('utf-8')       #Convert bytes to regular string
print(regular_str)                           #Print Output
Hello World

First, the hex_str is defined, which contains a sequence of characters representing a hexadecimal number. After that, the bytes.fromhex() method is called with hex_str as its argument that converts the string of hexadecimal characters into a byte object. The resulting byte_str variable contains the byte values represented by the hexadecimal characters.

The decode() method is called on the byte_str variable with 'utf-8' as its argument. This method converted the bytes object into a regular string using the UTF-8 encoding. The resulting regular_str variable contains the "Hello World" string. Finally, the regular_str variable is printed to the console using the print() function.

3. Using binascii Module

The binascii Module can be used for hex to String conversion. It follows the same steps as required for the above method. The main difference is at the point of converting a hexadecimal string to bytes.

import binascii                                  #Import module
hex_str = "48656c6c6f20576f726c64"               # Hex string
byte_str = binascii.unhexlify(hex_str)           # Convert hex string to bytes
regular_str = byte_str.decode('utf-8')           # Convert bytes to regular string
print(regular_str)                               # Print Output
Hello World

In this example, first, we imported the binascii module, which provides functions for converting between binary and ASCII formats. Then, the unhexlify() function converts the hex string to a bytes object. Finally, the bytes object is converted to a regular string using the decode() method and printed to the console.

4. Using codecs Module

The codecs‘s decode() method can be used for python hex to String conversion. It takes two arguments – bytes object and encoding type

import codecs                                     #Import module

hex_str = "48656c6c6f20576f726c64" 
hex_str_bytes = bytes(hex_str, encoding='utf-8') # Convert hex string to bytes
binary_string = codecs.decode(hex_str_bytes, "hex") # Convert bytes to regular string
print(str(binary_string, 'utf-8'))
Hello World

In this example, first, we imported the codecs module. Then, the bytes() function converts the hex string to a bytes object. Finally, the bytes object is converted to a regular string using the decode() method and printed to the console.

5. Using List Comprehension

Use list comprehension to convert hexadecimal to string in Python. Unlike the above methods, the hexadecimal string is not converted into bytes but into a decimal integer.

#Hex string
hex_str = "48656c6c6f20576f726c64"

#loop over the hexadecimal string to convert to
#a decimal integer and join the respective ASCII character
regular_str = ''.join([chr(int(hex_str[i:i+2], 16)) for i in range(0, len(hex_str), 2)])

#Print Output
print(regular_str)
Hello World

The list comprehension converted each pair of hexadecimal characters into a decimal integer using the int() function for this code. Then, the integer was converted to its corresponding ASCII character using the chr() function. Finally, joined the resulting list of characters into a single string using the join() method.

Please note that this method works for hex strings that have even number of digits and do not have prefix 0x.

6. Conclusion

All four methods produced the same output: the string "Hello World" as the input string was the same. Therefore, you can try different hexadecimal strings and convert them into regular strings using the above methods.

]]>
https://java2blog.com/python-hex-to-string/feed/ 0
Encode String to UTF-8 in Python https://java2blog.com/encode-string-to-utf-8-python/?utm_source=rss&utm_medium=rss&utm_campaign=encode-string-to-utf-8-python https://java2blog.com/encode-string-to-utf-8-python/#respond Sun, 25 Dec 2022 06:42:04 +0000 https://java2blog.com/?p=21948 The UTF-8 encoding is used by default in Python and represents 8-bit Unicode values. The upgrade to Python 3 saw a major change in using ASCII characters to Unicode characters by default for strings.

Encode String to UTF-8 in Python

This tutorial will demonstrate how to encode string to UTF-8 in Python.

Using the encode() function

To encode string to UTF-8 in Python, use the encode() function. encode() function is used to encode String in specific encoding.

See the code below.

s1 = "Java2Blog"
print(s1.encode('UTF-8'))

Output:

b’Java2Blog’

The encode() function in Python can be used to encode a string to the required encoding. This encoding, by default is UTF-8.

In Python 3, this returns a bytes type object. In the above example, the b prefix represents the same.

The same is not the case for Python 2. In this version, bytes and string are basically the same thing. So this, function is redundant since the string is already encoded.

We can observe the same in the code below.

s1 = "Java2Blog"
print s1.encode('UTF-8')

Output:

Java2Blog

Using the codecs.encode() function

To encode string to UTF-8 in Python, use the codecs.encode() function.

See the code below.

import codecs
s1 = "Java2Blog"
print(codecs.encode(s1,'UTF-8'))

Output:

b’Java2Blog’

Python has a standard module called codecs which defines the base class for all the encoders and decoders in Python. The access to internal Python codec registry is also provided by this module that manages the error handing and codecs.

The codecs.encode() function can be used to encode an object to the specified format. In the above example, we encode string to UTF-8 in Python using this function.

Conclusion

To conclude, we discussed different methods to encode string to UTF-8 in Python.

We discussed the basics of encoding in Python, highlighting the difference between Python 2 and Python 3.

The encode() function is used to encode string to UTF-8 in Python. The use of this function is highlighted for Python 2 and 3, and we compare the results of both.

The final method showed the use of the codecs module. This module contains the base for all encoders and we use the codecs.encode() function to encode string to UTF-8 in Python.

]]>
https://java2blog.com/encode-string-to-utf-8-python/feed/ 0
How To Do Line Continuation in Python https://java2blog.com/python-line-continuation/?utm_source=rss&utm_medium=rss&utm_campaign=python-line-continuation https://java2blog.com/python-line-continuation/#respond Thu, 22 Dec 2022 19:18:17 +0000 https://java2blog.com/?p=21828 Using Backslash (\) Operator

We can use \ operator for line continuation in string and number expression as follows.

Line Continuation in String

To do line continuation in Python Strings:

  • Use the backslash operator to do line continuation for writing strings in Python.
#use backslash in a string with single quotation marks
my_string1 = 'This code snippet \
explains line continuation \
in a string in python'
print(my_string1)

#use backslash in a string with double quotation marks
my_string2 = "This code snippet \
explains line continuation \
in a string in python"
print(my_string2)

#use backslash in a string with triple quotation marks
my_string3 = '''This code snippet \
explains line continuation \
in a string in python'''
print(my_string3)
This code snippet explains line continuation in a string in python
This code snippet explains line continuation in a string in python
This code snippet explains line continuation in a string in python

A backslash (\) is an explicit line break operator in Python that indicates that a line should continue.

It makes the code easier to read by breaking it into smaller chunks. It can help make debugging easier by allowing errors to be more easily identified and corrected. We can use it inside a string enclosed in single, double, and triple quotation marks.

We can use the operator in conditions, and loops, but not in comments. We used the backslash (\) operator inside three strings: string1, string2, and string3 enclosed in single, double, and triple quotation marks respectively.

All the strings were printed on the same single line on the console.

Line Continuation in Number Expression

To do line continuation in Python Numeric expressions:

  • Use the \ operator to explicitly split lines in the number expressions.
number1 = 5 + 2.5 - 1
number2 = 5 \
         + 2.5 \
         - 1
print("Without line continuation, the number is " + str(number1))
print("With line continuation, the number is " + str(number2))
Without line continuation, the number is 6.5
With line continuation, the number is 6.5

We have already discussed the backslash operator while learning its use in Line Continuation in String.

In this program, we explained the line continuation in a number expression. Using two expressions, we added 2.5 to 5, subtracted 1 from the result, and stored the final results in the number1 and number2 i.e., with and without line continuation.

On the execution, both techniques displayed the same output, but the line continuation made the code easier to understand.

Using Parentheses ()

We can use () for line continuation in string and number expression as follows.

Line Continuation in String

  • Use the parentheses to do line continuation in Strings in Python.
my_string = ("This code snippet "
             "explains line continuation "
             "in a string in python")
print(my_string)
This code snippet explains line continuation in a string in python

Parentheses is an implicit line continuation operator in Python that automatically inserts a line break and indentation when it is encountered. It is useful for writing long expressions, as in mathematics.

We used parentheses to make my_string easily readable by breaking it into chunks. On printing, it displayed whole string on a single line on the console.

Line Continuation in Number Expression

  • Use the parentheses to implicitly split lines in the Python number expressions.
number1 = 5 + 2.5 - 1
number2 = (5
           + 2.5
           - 1)
print("Without line continuation, the number is " + str(number1))
print("With line continuation, the number is " + str(number2))
Without line continuation, the number is 6.5
With line continuation, the number is 6.5

We covered the parentheses while explaining the code snippet for line continuation in string using parentheses. We solved a mathematical expression using parentheses (as we solved using the backslash (\) operator).

That’s all about how to do line continuation in Python.

]]>
https://java2blog.com/python-line-continuation/feed/ 0
Convert List to Comma Separated String in Python https://java2blog.com/convert-list-to-comma-separated-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=convert-list-to-comma-separated-string-python https://java2blog.com/convert-list-to-comma-separated-string-python/#respond Fri, 16 Dec 2022 18:24:32 +0000 https://java2blog.com/?p=21833 Use .join() Method

To convert a list to a comma separated string in Python, use the .join() method. join() method takes all elements in an iterable and joins them into one string with delimiter as separator.

list_of_strings = ['string_one', 'string_two', 'string_three']
comma_separated_strings = ','.join(list_of_strings)
print(comma_separated_strings)
string_one,string_two,string_three

First, we created a list having string-type elements and named that list list_of_strings. Next, we used the .join() method to join all list elements into strings using a comma as a separator. This method took an iterable as a parameter, which is list_of_strings, for this code example.

Here, iterable means the objects which can return their members/elements one at a time. We used a comma as a separator, but you can use a separator of your choice; it can be #, whitespace, etc.

Suppose the list contains non-string elements, such as int, bool, None, etc. Now, using the .join() method only will result in an error saying TypeError: sequence item 1: expected str instance, int found.

To handle this scenario, we can use the .join() with the map() method, as demonstrated in the following section.

Use .join() with map() Method

To convert a list having string and integer type elements to a comma separated strings in Python:

  • Use the map() method to transform the data type of all list elements to string.
  • Use the .join() method to join all the list elements (now of string data type) and separate them with a comma.
list_of_alphanumeric = ['string_one', 10, 'string_two', 'string_three']
comma_separated_strings = ','.join(map(str, list_of_alphanumeric))
print(comma_separated_strings)
string_one,10,string_two,string_three

In the previous section, we learned about the .join() method while converting a list_of_strings to comma-separated strings. Here, we used the map() method to map every list element to a string type value.

Once the mapping is performed on all list elements, we pass this map type object to the .join() method to join them separated by a comma.

Here, map(str, list_of_alphanumeric) maps the type of every element of list_of_alphanumericlist where every element is passed to str() function as its parameter.

Use .join() with List Comprehension

There is an alternative of using .join() with map() method, which is using .join() method with list comprehension as follows:

  • Use a list comprehension to iterate over each element of the list. In each iteration, pass the list element to str() for type casting.
  • Once all elements are cast to string data type, pass the converted list to the .join() method to join all the list elements separated by a comma.
list_of_alphanumeric = ['string_one', 10, 'string_two', 'string_three']
comman_separated_strings = ','.join([str(x) for x in list_of_alphanumeric])
print(comman_separated_strings)
string_one,10,string_two,string_three

After creating a list, we used list comprehension, which looped over the elements of the list_of_alphanumeric. Finally, we passed the current element to the str() method for type casting in each iteration. Here, type casting means changing the element’s datatype from one another.

Next, we passed the transformed list having all string-type elements to the .join() method, which joins all the elements by separating them using the given separator. We used , as the separator; you can use whatever you want.

That’s all about how to convert list to comma separated Strings in Python.

]]>
https://java2blog.com/convert-list-to-comma-separated-string-python/feed/ 0
Count Occurrences of Character in String in Python https://java2blog.com/count-occurrences-of-character-in-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=count-occurrences-of-character-in-string-python https://java2blog.com/count-occurrences-of-character-in-string-python/#respond Fri, 09 Dec 2022 10:06:23 +0000 https://java2blog.com/?p=21682 Using count() Method

Use String’s count() method to count occurrences of character in String in Python e.g. my_string.count(character). count() method returns number of occurrences of the character in String.

my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'
count = my_string.count(character)
print(f'Occurrences of character \'{character}\': {count}')

We will get the following result after running the above program.

Occurrences of character 'c': 7

The count() is a conventional method in Python. It holds a substring, start, and end as arguments and returns the count of appearances of any element in an iterable object. We used the count() method to count the occurrences of the character in my_String.

Using Naive for loop

To count the occurrences of a character in a string in Python:

  • Use for loop to iterate over each character of input String.
  • For each character, use the if statement to check if supplied character appears in String.
  • Increment the count by 1 if character exists in String.
my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'
count = 0

for element in my_string:
    if element == character:
        count+=1

print(f'Occurrences of character \'{character}\': {count}')

We will get the below output on the successful execution of the above program.

Occurrences of character 'c': 7

We used for loop to iterate over every element in my_string.

We incremented the count by 1 when the character appeared in my_string using an if statement.

Using List Comprehension

To calculate the occurrences of a character in a string in Python:

  • Use for loop to iterate every character of input string.
  • Append the element to a new list if the required character appears in string.
  • Use the len() method to find the occurrence of the character in string.
my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'

count = len([
    element for element in my_string
    if element == character
])

print(f'Occurrences of character \'{character}\': {count}')

The code above will print the following output on the console:

Occurrences of character 'c': 7

List Comprehension is a static construct for creating lists using a concise notation to make code more readable and efficient. It takes an existing iterable object and applies an expression, filter, or function to its every element. The result of that expression or function is then added to a new list.

We applied the list comprehension on my_string as:

  • Iterated every element of my_string.
  • Applied a filter to check if my_string contains the character.
  • Created a new list of elements based on the above condition.

Once we got the list, we used the len() method to store its length in the count.

Using re.findall() Method

To get a count of occurrences of a character in a string in Python:

  • Import Python library re.
  • Use re.findall() to create a new list of all matches of the character in my_string
  • Use len() to find the length of the new list.
import re
my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'
count = len(re.findall(character, my_string))
print(f'Occurrences of character \'{character}\': {count}')

Now we will get the following output:

Occurrences of character 'c': 7

Python regular expression library re is a Python module that supports compiling and executing regular expressions. It provides several functions for finding and manipulating strings using regular expressions.

The re.findall() method of the re library locates all the matches for a pattern in a string and returns a list of all those matches. We used it to locate all the matches of the character in my_string and created a new list of those matches.

On the list returned by re.findall(), we applied len() to get the count.

Using for loop with re.finditer() Method

To get the occurrence frequency of a character in a string:

  • Import Python library re.
  • Use re.finditer() to create a new list of all matches of the required character in input String.
  • Use for loop to iterate over every element of the new list.
  • Inside the for loop, increment count by 1.
import re

my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'
count = 0

for element in re.finditer(character, my_string):
    count += 1

print(f'Occurrences of character \'{character}\': {count}')

The above code will print the following output on the console:

Occurrences of character 'c': 7

We discussed re while explaining the code using the re.findall() method.

The re.finditer() method is used to find all possible matches for a regular expression. A match object is created for each match, and each object contains a count of the character positions in the string that the pattern matched. It returns a generator object that produces match objects.

We used for loop to iterate the objects returned by re.finditer() and incremented the count on each iteration.

Use the lambda Function with map()

To get the occurrence frequency of a character in a string in Python:

    • Use the lambda function to return 1 if current character in string is equal to supplied character e.g. lambda c: 1 if character in c else 0, my_string.
  • Use the map() function to apply the lambda function to every element of my_String.
  • Use the sum() function to sum up all the occurrences returned by the map() function.
my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'

count = sum(map(lambda c: 1 if character in c else 0, my_string))
print(f'Occurrences of character \'{character}\': {count}')

The execution of the above code will give us the following output.

Occurrences of character 'c': 7

A lambda function is a small anonymous function because it is undeclared with the standard def keyword.

It can take any number of arguments but can have only one expression. It is used when a function is needed for a short period.

In the lambda function, we used an expression 1 if character in c else 0 that returns 1 if the character appeared in c else 0.

The map() function in Python is a built-in function that allows you to apply a function to every item in an iterable object. It holds a function and iterables and returns an iterator object.

For example, we applied the lambda function to each element of my_String using the map() function.

Once we got an iterator object, we used the sum() function that added together all the values of the map() function and stored the sum in the count.

Use collections.Counter() Method

To count the occurrence of a character in a string:

  • Use the collections.Counter() function to create a counter object that contains the occurrence frequency of items in my_string.
  • Use count[character] to get the value of the character from the counter object.
from collections import Counter

my_string = "This code snippet counts occurrences of a character in a string in python"
character = 'c'
count = Counter(my_string)
print(f'Occurrences of character \'{character}\': {count[character]}')

We will get the below output on the successful execution of the above program.

Occurrences of character 'c': 7

The collections package in Python is a module that provides specialized container datatypes. These containers are highly optimized for performance and memory usage.

It provides classes that allow developers to create and manage complex data structures with minimal effort. From this package, we imported its Counter() class.

The collections.Counter() function creates a counter object that counts the occurrence frequency of items in a sequence.

The items are grouped by the value returned by their key function. The Counter class is a mutable subclass of dict but keeps the values in an integer key-value pair.

We applied the function on my_string to make key-value pairs of characters and their occurrence frequency. We extracted the value of the character from the counter object count using count[character].

]]>
https://java2blog.com/count-occurrences-of-character-in-string-python/feed/ 0
Find Character in String in Python https://java2blog.com/find-character-in-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=find-character-in-string-python https://java2blog.com/find-character-in-string-python/#respond Wed, 07 Dec 2022 18:44:26 +0000 https://java2blog.com/?p=21702 Using find() Method

To find the character in a string in Python:

  • Use the find() method to find the index of the first occurrence of the supplied character in the input String.
  • Use an if statement to check if the returned index is not -1; if so, print that index; otherwise, print an error.
my_string = "character"
character = 'a'

if my_string.find(character) != -1:
    print(f'\'{character}\' in \'{my_string}\''
          f' exists at index {my_string.find(character)}')
else:
    print(f'\'{character}\' does not exist in \'{my_string}\'')

On execution of the program, we will get the following output.

'a' in 'character' exists at index 2

The find() is a built-in method in Python that searches for a substring in a string. It returns the index of the first occurrence of the substring or -1 if not found. It holds:

  • The substring argument is required and used to search it in the given string.
  • The start and end arguments are optional and specify the starting and ending indexes from which to search for the substring. If these arguments are not specified, then it searches from 0 (the beginning) to len(string)-1 (the end).

We applied the find() method on my_string to get an index of the first matched occurrence of the character.

We used an if statement to handle the returned value of -1. If the find() method returned -1, we printed the index of the matched occurrence. Otherwise, the program jumped to the else statement.

If we specify the start and end as:

my_string = "character"
character = 'c'

if my_string.find(character, 2, 5) != -1:
    print(f'\'{character}\' in \'{my_string}\''
          f' exists at index {my_string.find(character, 2, 5)}')
else:
    print(f'\'{character}\' does not exist in \'{my_string}\'')

The program will print the following output on the console:

'c' does not exist in 'character'

Now the find() method searched the first occurrence of the character in my_string from start=2 to end=5, i.e., ara (excluding the fifth index). As no character=c, the program jumped on the else block and printed the error message.

Using index() Method

To locate the character in a string in Python:

  • Use the index() method to find the index of the first occurrence of the supplied character in input string.
  • Use the try-except clause to handle the exception of no match.
my_string = "character"
character = 'a'
try:
    print(f'\'{character}\' in \'{my_string}\''
          f' exists at index {my_string.index(character)}')
except Exception as e:
    print(e)

When we execute the program, we will get the following output.

'a' in 'character' exists at index 2

The index() is a built-in method in Python and is like the find() method that we discussed earlier when explaining the code snippet using the find() method. But it raises an exception called ValueError when it does not find any match.

We applied the index() method on my_string to get an index of the first matched occurrence of the character.

To handle the exception, we used a try-except statement. When no exception occurred, the try clause successfully printed the index of the first occurrence of the character in my_string. In case of an exception, the program jumped to the except clause to print the reason for the exception.

To specify the start and end in the index() method:

my_string = "character"
character = 'c'
try:
    print(f'\'{character}\' in \'{my_string}\''
          f' exists at index {my_string.index(character, 2, 5)}')
except Exception as e:
    print(e)

Now we will get the following output:

substring not found

Now, after specifying start=2 and end=5, the index() method did not find any occurrence of the character. So, the program jumped to the except statement. The except statement excepted the Exception returned by the index() method as e. Inside the clause, we printed the ValueError.

Until this point, we have learned about finding a character's first occurrence in a string. Next, learn to find multiple occurrences of a character` in a string.

Using for Loop with re.finditer() Method

To get the multiple occurrences frequency of a character in a string:

  • Import Python library re.
  • Use the in keyword to test if input string contains the supplied character.
  • Use re.finditer() to create a new list of all matches of the character in string.
  • Use the for loop to iterate over every element of the new list.
  • Inside the for loop, use element.start() to get the indexes of every occurrence.
import re
my_string = "character"
character = 'a'

if character in my_string:
    print(f'\'{character}\' is located in \'{my_string}\' at indexes:')
    for element in re.finditer(character, my_string):
        print(element.start())
else:
    print(f'\'{character}\' does not exist in \'{my_string}\'')

On execution, the above code will print the following output on the console:

'a' is located in 'character' at indexes:
2
4

The in keyword is a Python operator that tests if an iterable object container contains a specific value and is equivalent to the contains() method of the built-in str module.

We place an infix operator between two operands: the value to be tested and the sequence to test it against. It does not return any index, but True if the value exists, and False if not.

We used the in operator taking character and my_string as operands. If the character appeared in my_string, we used the if statement to run the further program. Otherwise, the else statement printed a message of no match.

We imported the re library, a Python regular expression library. It provides regular expression matching operations to support string-processing functions.

The re library provides the re.finditer() method that finds all occurrences of a pattern in a string. It creates a match object for each occurrence, and each object contains a count of the character positions in the string that the pattern matched. Finally, it returns an iterator of match objects.

We used the re.finditer() to create match objects of the occurrences of the character in my_string and used the for loop to iterate over every element of re.finditer().

Inside the for loop, we printed the index of every occurrence using the element.start() method.

Using list comprehension

To find multiple occurrences of character in String:

  • Use list comprehension to iterate over each character of given String with enumerate().
  • For each character, compare it with given character.
  • If condition is met, return the index.
  • Result will be list of the indices of character in the String.
def findOccurrences(s, ch):
    return [i for i, character in enumerate(s) if character == ch]

str = "Java2blog"
ch ='a'
print(findOccurrences(str,ch))
[1,3]

We defined custom function named findOccurrences() which takes input as String and character.

We used enumerate() function to get index of current iteration.

enumerate() function takes a iterable as input and returns tuple with first element as index and second element as the corresponding item.

On each iteration, we checked if current character is equal to a. If yes, we returned that index.

Resultant list contains all the indexes of character in the String.

That’s all about how to find character in String in Python.

]]>
https://java2blog.com/find-character-in-string-python/feed/ 0
Remove Substring from String in Python https://java2blog.com/remove-substring-from-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=remove-substring-from-string-python https://java2blog.com/remove-substring-from-string-python/#respond Mon, 05 Dec 2022 07:29:08 +0000 https://java2blog.com/?p=21669 Use replace() Method

To eliminate a substring from string in Python:

  • Define and initiate my_string.
  • Declare substring to remove it from my_string.
  • Use replace() method to remove substring from string. e.g. my_string = my_string.replace(substring, "")
my_string = "The code $#jc@ snippet removes a substring $#jc@ from a string in python."
substring = "$#jc@ "

print(f'My String: {my_string}')

my_string = my_string.replace(substring, "")

print(f'Substring: {substring}\n'
      f'My New String: {my_string}')

The code above will print the following output on the console:

My String: The code $#jc@ snippet removes a substring $#jc@ from a string in python.
Substring: $#jc@ 
My New String: The code snippet removes a substring from a string in python.

We tried removing the substring from my_string.

The replace() is a built-in method in Python that holds two or more parameters and a __count of the occurrences of a substring.

If specified, at most __count substitutions are performed from left to right. Finally, the method replaces all the occurrences of the substring old with new and returns a copy.

We used replace(substring, "") on my_string as:

  • __count by default is -1, but you can set it using replace(my_string, "", 2).
  • The __old string is the substring.
  • The __new string "" is nothing but an empty string.

F-strings, also known as "formatted string literals", is a new way in Python to format strings. We used it to provide a better display of information as f'Input: {my_string}'.

Use the split() Method with for loop

To get rid of a substring from a string in Python:

  • Declare an empty string my_new_string = ""
  • Use split() to split my_string by substring into array str_arr.
  • Use the for loop to iterate over each element of str_arr
  • Concatenate every element of my_string with my_new_string
my_string = "The code $#jc@ snippet removes a substring $#jc@ from a string in python."
substring = "$#jc@ "

print(f'My String: {my_string}')

my_new_string = ""
str_arr = my_string.split(
    sep=substring,
    maxsplit=2
)

for element in str_arr:
    my_new_string += element

print(f'Substring: {substring}\n'
      f'My New String: {my_new_string}')

The code above will print the following output on the console:

My String: The code $#jc@ snippet removes a substring $#jc@ from a string in python.
Substring: $#jc@ 
My New String: The code snippet removes a substring from a string in python.

Python String Concatenation requires declared and initialized strings. my_new_string is "" that is just an empty string.

We used split() to discard the substring from my_string.

The split() method performed as:

  • Took sep as a delimiter.
  • Took maxsplit (default is -1).maxsplit defines number of maxium split.
  • Discarded maxsplit occurrences of sep from the resultant string.
  • Split the string at maxsplit points.
  • Returned a copy of a list of strings(s).

We used a for loop to iterate over all the elements of the my_string.

We used += to join the String.

In Python, we can perform String Concatenation using +=, holding the resultant string on the left side as my_new_string = my_string.

If you want to remove only first occurrence of substring, then you can use maxsplit as 1 while using split() and it won’t remove other occurrences of the substring.

my_string = "The code $#jc@ snippet removes a substring $#jc@ from a string in python."
substring = "$#jc@ "

print(f'My String: {my_string}')

my_new_string = ""
str_arr = my_string.split(
    sep=substring,
    maxsplit=1
)

for element in str_arr:
    my_new_string += element

print(f'Substring: {substring}\n'
      f'My New String: {my_new_string}')

The code above will print the following output on the console:

My String: The code $#jc@ snippet removes a substring $#jc@ from a string in python.
Substring: $#jc@ 
My New String: The code snippet removes a substring $#jc@ from a string in python.

If you want to remove all occurrences of the substring, don’t pass maxsplit parameter as it is defaulted to -1 and that means there won’t be any limit to number of splits.

Use split() with join() Method

To eliminate a substring from a string in Python:

  • Use split() to remove the substring from my_string
  • Use the join() method to join every element of the list my_string
my_string = "The code $#jc@ snippet removes a substring $#jc@ from a string in python."
substring = "$#jc@ "

print(f'My String: {my_string}')

my_string = my_string.split(
    sep=substring,
    maxsplit=2
)
my_string = "".join(my_string)

print(f'Substring: {substring}\n'
      f'My New String: {my_string}')

The code above will print the following output on the console:

My String: The code $#jc@ snippet removes a substring $#jc@ from a string in python.
Substring: $#jc@ 
My New String: The code snippet removes a substring from a string in python.

We covered split() while explaining the code using the split() method.

We used the join() method in the above code snippet. It took an iterable object of strings to concatenate them where the delimited string is the one that provides that method. For example, we concatenated the elements of my_string using the delimiter "".

Use re.sub() Method

To eliminate a substring from a string in Python:

  • Import re
  • Use re.sub() to remove the substring from my_string
import re

my_string = "The code $#jc@ snippet removes a substring $#jc@ from a string in python."
print(f'My String: {my_string}')

my_string = re.sub(
      pattern='\W\Wjc\W ',
      repl='',
      string=my_string
)
print(f'My New String: {my_string}')

The code above will print the following output on the console:

My String: The code $#jc@ snippet removes a substring $#jc@ from a string in python.
My New String: The code snippet removes a substring from a string in python.

We imported re library that provides regular expression-matching operations

The re.sub() is a method of the re library that substitutes occurrences of a pattern found in a string. It held:

  • The original string.
  • A replaceable string pattern.
  • A count (default is 0).
  • A repl string to replace the count times pattern.

You may wonder why we write the pattern as \W\WJC\W because the re library cannot nest special characters directly; we replaced each with the escape sequence \W.

We used re.sub() to replace the count times pattern of my_String with "". The count by default is 0 and it will replace all the occurrences but you can set it using count=1,2,3,....

That’s all about how to remove substring from String in Python.

]]>
https://java2blog.com/remove-substring-from-string-python/feed/ 0
Prefix b Before String in Python https://java2blog.com/prefix-b-before-string-python/?utm_source=rss&utm_medium=rss&utm_campaign=prefix-b-before-string-python https://java2blog.com/prefix-b-before-string-python/#respond Tue, 29 Nov 2022 13:01:43 +0000 https://java2blog.com/?p=20844 Prefix b Before String in Python

Prefix b before String denotes a byte String. By putting b before String, you can convert String to bytes in Python.

The upgrade from Python 2 to Python 3 was considered a major change as many new features were introduced and quite a few changes were done to the existing types. One such change was the distinction between bytes and strings in Python 3.

In Python 2, bytes and strings were considered the same, and both were used interchangeably. They were considered as a collection of octets in this version which means that they were ASCII encoded. To create Unicode string literals one had to use the u prefix before the string.

However, Python 3 introduced a major change as strings were now considered a collection of Unicode characters. This provided users with a wide range of characters to choose from and represent strings as texts.

Bytes are treated as a separate entity in Python 3 and we have to use the prefix b before string in Python to create them. The b prefix tells the interpreter to create a bytes object.

For example,

s = b'bytes string'
print(s)

Output:

b’bytes string’

In the above example, we can notice the prefix b before string in Python which indicates that it is a byte string.

We can also use the bytes() and bytearray() functions to create a bytes instance of the required sequence. Here we need to specify the source for the object. If the source is a string, we need to specify the encoding of the same as well.

The difference between the above-mentioned functions is that the object returned by the bytes() function cannot be modified whereas the object returned by the latter can be altered.

Conclusion

In this tutorial, we discussed the prefix b before string in Python. First, we highlighted the difference in Python 2 and 3 regarding the treatment of bytes. We discussed the distinction between bytes and strings in Python 3 and how the prefix b before string in Python can create a bytes instance. We also highlighted the use of bytes() and bytearray() functions.

]]>
https://java2blog.com/prefix-b-before-string-python/feed/ 0
Get String Between Two Characters in Python https://java2blog.com/get-string-between-two-characters-python/?utm_source=rss&utm_medium=rss&utm_campaign=get-string-between-two-characters-python https://java2blog.com/get-string-between-two-characters-python/#respond Mon, 28 Nov 2022 13:13:28 +0000 https://java2blog.com/?p=21427 Using the string-slicing technique

To get String between two characters in Python:

  • Use String’s find() method to find indices of both the characters.
  • Use String’s slicing to get String between indices of the two characters.
def getSubstringBetweenTwoChars(ch1,ch2,str):
    return s[s.find(ch1)+1:s.find(ch2)]

s = 'Java2Blog'
s2= getSubstringBetweenTwoChars('J','g',s)
print(s2)

Output:

ava2Blo

In the above example, we found the position of characters J and g using the find() function and used the string-slicing technique to extract the string between these characters.

String’s find() method returns index of specified value and returns -1 if value is not present.

We used String slicing to find substring between indices of the two character.

String slicing refers to the technique of extracting parts of strings using the character’s index. We specify the start, end, and step values for string slicing within the square brackets. The step value specifies the increment between two successive values and is set to one by default.

Since start index is included while doing string-slicing, we used +1 for first character e.g. s.find('ch1')+1 as we didn’t want to include first character in the substring.

Using Regular Expressions

Use re’s search() method to get substring between two characters using regular expression, e.g. re.search(ch1+'(.+?)'+ch2, str).

import re

def getSubstring(ch1,ch2,str):
    m = re.search(ch1+'(.+?)'+ch2, s)
    if m:
        s2 = m.group(1)
    return s2

s = 'Java2Blog'

s2 = getSubstring('J','g',s)
print(s2)

We used re.search() method to get substring between two characters.

re.search() searches the String for a match and returns re.match object. If no matches found, it will return None.

The first argument we passed is regular expression and second argument is String in which you want to search on the based of regular expression.

We extracted matched String from re.match object m using m.group(1).

Here is pictorial representation of the regular expression:

Get String between two characters using regular expressions

m.group(0) returns fully matched String while m.group(1) returns first captured group in input String.

Using the split() function

  • Use split() to split the String based on first character.
  • From the extracted two parts, use the second part and split it again using the second character.
  • From the returned parts, the first one is the required string between the two characters.
def getSubstringBetweenTwoChars(ch1,ch2,str):
    return s.split(ch1)[1].split('ch2')[0]
s = 'Java2Blog'
s2= getSubstringBetweenTwoChars('J','g',s)
print(s2)

Output:

ava2Blo

The split() function in Python can be used to split a string into two parts at the position of a specific character.

We used split() method to split the String Java2blog in two parts based on first character i.e. J. It returned list with two elements.i.e J and ava2blog.

We then again used split() method to split second part of the list ava2blog based on second character g. It returned list with two elements. ava2Blo and g.

First element of the concluded list is the substring between two characters J and g in String Java2blog

Conclusion

To conclude, we discussed several methods in this article to get string between two characters in Python.

In the first method, we used the string-slicing technique. In this method, we find the positions of the two characters and extract the required string between them using this technique.

The next method discusses the use of the re library for the same. This method uses regular expressions to find the required substring using a regex pattern with the re.search() function. In the final method, we used the split() function consecutively to split and get the string between two characters in Python.

]]>
https://java2blog.com/get-string-between-two-characters-python/feed/ 0