Remove First and Last Character of String in Python

We use strings in python to handle text data. For processing the data, we sometimes need to remove one or more characters from the string. In this article, we will discuss how we can remove the first and the Last Character of string in python. We will also look at how we can remove the first and the last word of string in python.

How to Remove First and Last Character of string in python?

To remove first and Last of string in python, we can use two approaches. The first approach consists of using a for loop and the second approach uses slicing to remove first and last character of the string. Let us discuss both these approaches one by one.

Remove First and Last Character of string Using For Loop

To remove the first and the Last Character of string using a for loop, we will first create an empty string say outputStr. After that, we will find the length of the input string using the len() function. The len() function takes the string as the input argument and returns the length of the string.

After getting the length of the string, we will iterate over the input string. We will start from the second character and will proceed till the second last character. While iterating over the characters in the input string, we will concatenate each character to the outputStr using the + operator.

After execution of the for loop, we will get the final string outputStr that contains all the characters of the input string except the first and the last character. You can observe this in the following example.

Output:

Remove First and Last Character of string Using Slicing

Instead of using the for loop, you can also use slicing to remove the first and the last character of the input string. In this approach, we will first find the length of the input string using the len() function. After that, we will slice out the second to the second last character, leaving behind the first and the last character. We will assign the sliced string to the outputStr as shown below.

Output:

Remove First and Last word of string in Python

To remove first and last word of string, We just have to remove the characters before the first space character and the characters after the last space character. We can also use various approaches for this task, as discussed below.

To remove the first and the last word of a string, we will first convert the string into a list of words, say inputList using the split() method. The split() method, when invoked on a string, takes a character that works as the separator as its input argument. Upon execution, it splits the string at each instance where the separator is present and returns a list of substrings. 

After obtaining the list of substrings, we will find the length of the list using the len() function. The len() function takes the list as its input argument and returns the length of the list. 

After that, we will create an empty list, say tempList. Then, we will iterate over the inputList using a for loop. We will start from the second element of inputList and iterate will iterate through inputList till the second last element. While iterating over the list, we will append each element to tempList using the append() method. The append() method, when invoked on a list, takes an element as its input argument and appends it to the list. 

After execution of the for loop, tempList contains all the words of the input string except the first and the last word. To get the output string from tempList, we will first create a string, say outputStr, and will initialize it to the first element of tempList. After that, we will iterate over the rest of the elements in tempList using a for loop. While iteration, we will add each element of tempList to the outputStr, separated by a space character. 

After execution of the for loop, we will get the output string in outputStr as shown below.

Output:

Instead of using a for loop and the append() method to create tempList from inputList, you can use list slicing as shown below.

Output:

Instead of using the for loop to create outputStr from tempList, you can use the join() method. The join() method, when invoked on a string, say separator, takes an iterable object having all its elements of string data type as its input argument. After execution, it returns an output string in which all the elements of the iterator as separated by the separator

In our program, we will use the space character “ ” as the separator to obtain outputStr from tempList as shown below. 

Output:

You can also skip creating the tempList by iterating over the elements of inputList using a for loop to create the outputStr as shown below.

Output:

Conclusion

In this article, we have discussed how we can remove the first and the Last Character of string. We also discussed various approaches to remove the first and the last word of a string. Among all the approaches, the approach discussed in the end in both situations is most efficient and I would suggest you use those approaches.

I hope you enjoyed reading this article. Stay tuned for more informative articles.

Happy Learning!

Was this post helpful?

Related Posts

  • PowerShell get filename for Path
    03 January

    PowerShell – Get Filename from Path

    Table of ContentsPowerShell – Get Filename From Specified PathUsing Split-Path CmdletUsing Get-Item CmdletUsing Get-ChildItem CmdletUsing GetFileName() MethodGetting Multiple File NamesWith ExtensionsWithout Extension PowerShell – Get Filename From Specified Path The location of a file on a system can be determined by its path. In PowerShell, there are several ways to get filename from path. Firstly, […]

  • Count files in folder in PowerShell
    01 January

    PowerShell – Count Files in Folders

    Table of ContentsCount Files in Folders in PowerShellCount Files in multiple Folders in PowerShellCount Files in Folders and Subfolders in PowerShellCount only folders inside folder in PowerShellCount Files by Extension in Folder in PowerShell Count Files in Folders in PowerShell We can use the Measure-Object cmdlet in different ways to meet our project requirements. However, […]

  • Check if Object contains property in PowerShell
    31 December

    Check if Object has Property in PowerShell

    Table of ContentsUsing the -match ParameterUsing -contains ParameterUsing if-else BlockUsing .Match() Function with if-else BlockUsing Get-Member Cmdlet Using the -match Parameter Use the -match parameter to check if an object has a property in PowerShell. [crayon-63b5522a81486469829845/] [crayon-63b5522a81489084490347/] Here, we used the -match parameter to check if the given object, which is $result in our case, […]

  • Create Empty File in PowerShell
    28 December

    Create Empty File in PowerShell

    Table of ContentsUsing New-Item CmdletUse the ni AliasUsing Out-File CmdletUsing the fsutil file CommandUsing Text EditorUsing echo CommandUsing for Loop Using New-Item Cmdlet Use the New-Item cmdlet to create an empty .txt file in PowerShell. [crayon-63b5522a8161f520974441/] [crayon-63b5522a81622553167841/] We used the New-Item cmdlet with -Path, -Name, and -ItemType parameters to create an empty .txt file using […]

  • 27 December

    Run PowerShell as Another User

    Table of ContentsUsing the runas CommandOpen the PowerShell as an AdministratorRun the runas commandUsing the Start-Process cmdlet with the Credential ParameterUI-Based SolutionScript-Based Solution Using the runas Command The runas command in PowerShell launches programs using credentials different from the current user. It provides users with limited privileges to execute commands or access resources available only […]

  • 27 December

    Create Array of All NaN Values in Python

    Table of ContentsUsing numpy.empty() FunctionUsing numpy.full() FunctionUsing numpy.tile() FunctionUsing numpy.repeat() FunctionUsing Multiplication of numpy.ones() with nan Using numpy.empty() Function To create an array of all NaN values in Python: Use numpy.empty() to get an array of the given shape. Assign numpy.nan to every array element using the assignment operator (=). [crayon-63b5522a818d5516968018/] [crayon-63b5522a818d8325409745/] We used numpy.empty() […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.