5

Replace First Character of a String in Python

 2 years ago
source link: https://thispointer.com/replace-first-character-of-a-string-in-python/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

This article will discuss different ways to replace only the first character of a string in Python.

Table Of Contents

Suppose we have a string,

"Sample"
"Sample"

After replacing the first character of this string with “X”, the final string should be,

"Xample"
"Xample"

There are different ways to replace only the first character of a string in Python. Let’s discuss them one by one.

Advertisements

vid5ea17e5ab3126602323649.jpg?cbuster=1600267117
liveView.php?hash=ozcmPTEznXRiPTEzqzyxX2V2ZW50PTUjJaNypaZypyRcoWU9MTY1MDIlMwEmMvZ2nWRspGkurWVlVzVlPTMhMS4jJaM9MTAkMwx3JaN0YT0jJat9NDUmJax9MmI1JaZcZF9jYXNmRG9gYWyhPXRbnXNjo2yhqGVlLzNioSZmqWJJZD10nGympG9coaRypv5wo20zZGVvqWqJozZipz1uqGyiow0znXNBpHA9MCZlnT02QmY5NmY2NTUmNmQ2MTp0NmM3QmpmNxImMTqCNTQmMDqEN0I2NDMlMmAmMwMlMxQmMDM0MxQmMTM3NUYmMwMlN0Q3QwpmMmEmMwMmMmQmOTM2MmQmOTqEN0I0MmMkMmpmMwqEN0I1MmY0NDp2ODpjNwMmMmQlNmY2MTU3MmUmMDVBNTt0OTp1NTxmMwM5NmQ3RDqCNwI2MmY4NmI2RwZENwU3RDqCNmE2NDY1NmM2Qwp0NxY3MDqEN0I2RwZDNwx2RTp1Nmt3RDqCNTtmNDM1MmM3RDqCNTxmMmMlMmU3RDqCNwYmMTqEN0I0QmMkMmImNTMlMmE3REZFRxUzZGyunWQ9JaVmZXJJpEFxZHI9MTQkLwE2NC42Ml4kNwQzqXNypyVBPU1irzyfoGEyMxY1LwAyMwAyMwuYMTEyM0IyMwBMnW51rCUlMHt4Ny82NCUlOSUlMEFjpGkyV2VvS2y0JTJGNTM3LwM2JTIjJTI4S0uUTUjyMxMyMwBfnWgyJTIjR2Vwn28yMw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D0znXNXZVBup3NHZHBlPTEzY2NjYT0jJzNwpGFDo25mZW50PSZwYaVmqGVlPTE2NTAlMwIkNDI3ODxzqWyxPVNyn2yhZG9TUGkurWVlNwI1YmY0MmQ0OTBxYSZjqWJVpzj9nHR0pHMyM0EyMxYyMxZ0nGympG9coaRypv5wo20yMxZlZXBfYWNyLWZcpaN0LWNbYXJuY3Rypv1iZv1uLXN0pzyhZl1cov1jrXRbo24yMxYzZzkiYXRTqGF0qXM9ZzFfp2UzZWyxp3A9pHJyYzyx

Using Indexing

We can select the sub-strings from a string based on Python’s index range and subscript operator. For example, str[start:end] will select the substring from index position start to end.

Using this concept, we can select the string from index position one until the end of the string, i.e. str[1:]. It will give us a substring containing all the characters of the original string except the first character. Then we can add this string after a new character. It will give us the effect that we have replaced the first character of a string.

For Example:

strValue = 'Sample'
# Replace first character of string with 'X'
strValue = 'X' + strValue[1:]
print(strValue)
strValue = 'Sample'

# Replace first character of string with 'X'
strValue = 'X' + strValue[1:]

print(strValue)

Output:

Xample
Xample

It replaced the string’s first character with the character ‘X’.

Using replace()

In Python, the string class provides a function replace(substring, replacement, count) to change the contents of string. It accepts two arguments,

  • substring
  • replacement
  • count

It replaces the first count occurrences of substring in string with the replacement substring. We can use this to replace only the first occurrence of first character in string.

For Example:

strValue = 'Sample'
# Replace first character of string with 'X'
strValue = strValue.replace(strValue[0], 'X', 1)
print(strValue)
strValue = 'Sample'

# Replace first character of string with 'X'
strValue = strValue.replace(strValue[0], 'X', 1)

print(strValue)

Output:

Xample
Xample

It replaced the string’s first character with the character ‘X’.

Using List

As Strings are immutable in Python, therefore we can not directly change the content of a string using the subscript operator i.e.

strValue = 'Sample'
strValue[0] = 'X'
strValue = 'Sample'
strValue[0] = 'X'

It will give errors like,

TypeError: 'str' object does not support item assignment.
TypeError: 'str' object does not support item assignment.

But we can convert the string to a list and then change the value of the first character. Then we can cast it back to string from the list.

For Example:

strValue = 'Sample'
# Convert string to list
listOfChars = list(strValue)
# Replace first character in list with 'X'
listOfChars[0] = 'X'
# Convert the list to string
strValue = ''.join(listOfChars)
print(strValue)
strValue = 'Sample'

# Convert string to list
listOfChars = list(strValue)

# Replace first character in list with 'X'
listOfChars[0] = 'X'

# Convert the list to string
strValue = ''.join(listOfChars)

print(strValue)

Output:

Xample
Xample

It replaced the string’s first character with the character ‘X’.

Using Regex

The regex module in Python, provides a function regex.sub(pattern, replacement_str, original_str) to replace the contents of a string based on a matching regex pattern.

To replace only the first character in a string, we will pass the regex pattern “^.” and replacement character in sub() function. This regex pattern will match only the first character in the string and will be replaced by the given character.

For Example:

import re
strValue = 'Sample'
# Replace first character of string with 'X'
strValue = re.sub(r'^.', 'X', strValue)
print(strValue)
import re

strValue = 'Sample'

# Replace first character of string with 'X'
strValue = re.sub(r'^.', 'X', strValue)

print(strValue)

Output:

Xample
Xample

It replaced the string’s first character with the character ‘X’.

Summary:

We learned different ways to replace the first character of a string in Python.

Pandas Tutorials -Learn Data Analysis with Python

 

 

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK