Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Python string manipulation

# let us create a test string

testString1 = "Hello World!"
print "Original String: "+ testString1
# Print this string in lower case

# Converting a string to lower case
print "Converting to LowerCase"
print testString1.lower()

# Converting a string to upper case
print "Converting to Upper Case"
print testString1.upper()

# Capitalizing a string
# Only the first letter in the string will be capitalized
print "Capitalizing the String"
print testString1.capitalize()

# Trying to slice out a substring between given indexes
print "Substring from index 1 to 7"
print testString1[1:8]

#Substring from the start till character at index = 7 (start of string is index 0)
print "Substring from the start till character at index = 7 (start of string is index 0): "
print testString1[:8]

#Substring from the character at index = 7, till the end of the string (remember: start of string is index 0)
print "Substring from the character at index = 7, till the end of the string (remember: start of string is index 0): "
print testString1[7:]


#Find the position of a  substring within the string
#This gives us the first index during a left to right scan. If the string is not found, it returns -1
print "Find the index from which the substring 'llo' begins within the test string"
print testString1.find('llo')

print "Now, let's look for a substring which is not a part of the given string"
print testString1.find('xxy')

# Now, trying to find the index of a substring between specified indexes only
print "Now, trying to find a substring between specified indexes only: looking for 'l' between 4 and 9"
print testString1.find('l',4,9)

# rfind is used, to find the index from the reverse
# So, testString1.rfind('l') will look for the last index of l in the string
print "find('l') on the given string returns the following index (scanning the string from left to right):"
print testString1.find('l')

print "rfind('l') on the given string returns the following index (this scans the string from right to left):"
print testString1.rfind('l')

# Now let us try to replace/substitute a substring of this string with another string
print "Replacing World with Planet"
print testString1.replace("World","Planet")


# Now let us try to split the string, into separate words
# let us split it wherever there is a space
print "Splitting the string into words, wherever there is a space"
print testString1.split(" ")
print testString1.rsplit(" ")

# Remove leading and trailing whitespace characters
testString2 = "Hello World!  "
print "Current Test String=" + testString2
print "Length (there are whitespaces at the end):" + `len(testString2)`
print "Length after stripping "+ `len(testString2.strip())`
Comment

string manipulation in python

###############################################################################################
#
# This code snippet takes a string input and append suffixes based on a number of conditions
# Condtion:
#    1 if the lenght of the string is grater than 3 characters and is not already
#       ended with "ing" then add suffix "ing"
#    2 else if the lenght of the string is grater than 3 then add suffix "ly"
#
# The code snippet can be improved to include more business conditions.
################################################################################################


# input string.
s_word = input()

# suffix to add to the input string if the condition is met
# the condition is, the string length must be grater than 3
suffix1 = "ing"

# suffix to add to the input string when the condition is not met
suffix2 = "ly"

# Initialize result to the input string.
# The same input string will be retured if 
# None of the conditions are met.
result = s_word

# check if s_word is all letters
# you don't want to add "ing" or "ly" to string of numbers
if s_word.isalpha():

    # trim all leading or trailing spaces
    s_word = s_word.strip()

    #1 The string contains at least 3 characters/letters
    if len(s_word) >= 3:

        # Extract the last 3 character of the string
        str_end = s_word[-3:].lower()
        print(str_end)
        # Append suffix1 if the last 3 character of the string
        # do not already contains it
        if str_end != suffix1.lower():
            result = s_word+suffix1

        #2 Append suffix2 if the string already ends
        #  with suffix1
        else:
            result = s_word+suffix2

print(result)
Comment

Python String Operations

# Python String Operations
str1 = 'Hello'
str2 ='World!'

# using +
print('str1 + str2 = ', str1 + str2)

# using *
print('str1 * 3 =', str1 * 3)
Comment

PREVIOUS NEXT
Code Example
Python :: install web3 on python 
Python :: greater and less than in python 
Python :: django forms 
Python :: download button image streamlit 
Python :: 3d data visualization python 
Python :: python print not working 
Python :: selenium wait until 
Python :: django-filter for multiple values parameter 
Python :: lambda functions 
Python :: phyton "2.7" print 
Python :: color reverse 
Python :: oop in python 
Python :: stack python 
Python :: set intersection 
Python :: create an empty list in python 
Python :: leetcode python 
Python :: Python NumPy ravel function Syntax 
Python :: python string variable 
Python :: print all objects in list python 
Python :: data encapsulation in python 
Python :: why is c faster than python 
Python :: how to test that an exception was raise using pytest 
Python :: self keyword in python 
Python :: solving linear equation using numpy 
Python :: linked list python 
Python :: problem solving with python 
Python :: django form date picker 
Python :: get element by index in list python 
Python :: sys.argv python example 
Python :: matplotlib keyboard event 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =