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 in python

# The input() Always Return Type == ( String ) 
# So If You Wanna Take Just String Value From The User :-
name = input( "Enter Your Name: " )

if name.isdigit() :
  print( "integer" )
else :
  print( "string" )  
Comment

Basic String Functions in python

# Basic Functions
len('turtle') # 6

# Basic Methods
'  I am alone '.strip()               # 'I am alone' --> Strips all whitespace characters from both ends.
'On an island'.strip('d')             # 'On an islan' --> # Strips all passed characters from both ends.
'but life is good!'.split()           # ['but', 'life', 'is', 'good!']
'Help me'.replace('me', 'you')        # 'Help you' --> Replaces first with second param
'Need to make fire'.startswith('Need')# True
'and cook rice'.endswith('rice')      # True
'bye bye'.index('e')                  # 2
'still there?'.upper()                # STILL THERE?
'HELLO?!'.lower()                     # hello?!
'ok, I am done.'.capitalize()         # 'Ok, I am done.'
'oh hi there'.find('i')               # 4 --> returns the starting index position of the first occurrence
'oh hi there'.count('e')              # 2
Comment

{} string python

txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
txt2 = "My name is {0}, I'm {1}".format("John",36)
txt3 = "My name is {}, I'm {}".format("John",36)

#https://www.w3schools.com/python/ref_string_format.asp
Comment

python string

txt = "this is a wild string"

print(txt.replace("i", "x"))  # print string with all i characters replaced with x
print(txt.replace("i", "x", 2))  # print string with first two i characters found with x
print(txt.upper())  # print string in all uppercase letters
print(txt.lower())  # print string in all uppercase letters

print(ord('A'))  # print the ordinal value of a character
print(chr(95))  # print character from its ordinal value
print('Yes' * 5) # print string Yes 5 times

# Reference strings by index
print(txt[0])  # print first letter of string from starting index
print(txt[0:2])  # print first two letters from starting index
print(txt[1:])  # print all characters except the first letter
print(txt[0::2])  # print every second character
print(txt[::-1])  # print string in reverse
print(txt[-1])  # print the last character in a string
print(txt[-2:])  # print the last who characters in a string

# check if a wild is found in txt
if "wild" in txt:
  print("wild is found in txt")

# check if a blah is not found in txt
if "blah" not in txt:
  print("is not found in txt")

# Check if txt starts with this
if txt.startswith("this"):
  print("Starts with this")

# check if txt ends with ing
if txt.endswith("ing"):
  print("Ends with ing")

# Split a string into a tuple when the delimiter is first encountered
txt = 'random-data'

data_split = txt.partition('-')
print(data_split)
# output ('random', '-', 'data')

len(txt)  # Return length of string

# loop through each character in string
for char in txt:
  print(char)

# Display price with commas and 2 digit precision
price = 9749000
display_price = f"My price {price:,.2f}"
print(display_price)


fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']
fruits.count('apple')  # count number of apples found in list
# output 2
fruits.count('tangerine')  # count number of tangerines in list
# output 0
fruits.index('banana')  # find the first index of banana
# output 3
fruits.index('banana', 4)  # Find next banana starting a position 4
# output 6
fruits.reverse()  # reverse fruits array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']
fruits.append('grape')  # append grape at the end of array
fruits
# output ['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
fruits.sort()
fruits
# output ['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']

len(fruits)  # length of fruits array
# output 8

# loop and print each fruit
for fruit in fruits:
  print(fruit)
  
empty_set = set()

basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)                      # show that duplicates have been removed
# output {'orange', 'banana', 'pear', 'apple'}

# check if orange is in basket set
print('orange' in basket)
# output true

# convert a string to a set of letters - sets contains no duplicates
set_a = set('abcd')
set_b = set('bcde')

# the operations below returns new sets
# print letters in set_a but not in set_b - difference
print(set_a - set_b)
# output {'a'}

# print set letters that is in either set a or b - union
print(set_a | set_b)
# output {'a', 'c', 'e', 'b', 'd'}

# print letters that are in both set_a and set_b - intersection
print(set_a & set_b)
# output {'c', 'd', 'b'}

# print letters that are in set_a and set_b when the letters are found in a set but no the other set - symmetric_difference()
print(set_a ^ set_b)
# output {'a', 'e'}

# Creating dictionaries
dict1 = {'color': 'blue', 'shape': 'square', 'volume': 40}
dict2 = {'color': 'red', 'edges': 4, 'perimeter': 15}

# Creating new pairs and updating old ones
dict1['area'] = 25  # {'color': 'blue', 'shape': 'square', 'volume': 40, 'area': 25}
dict2['perimeter'] = 20  # {'color': 'red', 'edges': 4, 'perimeter': 20}

# Accessing values through keys - an KeyError will occur if the key does not exists
print(dict1['shape'])

# You can also use get, which doesn't cause an exception when the key is not found
dict1.get('false_key')  # returns None
dict1.get('false_key', "key not found")  # returns the custom message that you wrote

# Delete item key and return the value if the key does not exists a KeyError occurs
print(dict1.pop('volume'))

# Merging two dictionaries
dict1.update(dict2)  # if a key exists in both, it takes the value of the second dict
dict1  # {'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}

# Getting only the values, keys or both (can be used in loops)
dict1.values()  # dict_values(['red', 'square', 25, 4, 20])
dict1.keys()  # dict_keys(['color', 'shape', 'area', 'edges', 'perimeter'])
dict1.items()
# dict_items([('color', 'red'), ('shape', 'square'), ('area', 25), ('edges', 4), ('perimeter', 20)])

# create a shallow copy of dict1
dict3 = dict1.copy()
# dict3 = {'color': 'red', 'shape': 'square', 'area': 25, 'edges': 4, 'perimeter': 20}


Comment

string in python

# ways to dfefine string in python
string = "String"
string = str(string)

# Can Add strings
s1  = "Str"
s2 = "ing"
s = s1 + s2 # "String"
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

#Strings in python are surrounded by either single quotation marks, or double quotation marks.
print("This is a string")
print('i am also a string')
Comment

python string

>>> 'Py' 'thon'
'Python'
Comment

Python String

print("A Computer Science portal for ")
Comment

python string

#You can assign a multiline string to a variable by using three quotes:

a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
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 :: fetch row where column is missing pandas 
Python :: python save button 
Python :: baeutifulsoup find element with text 
Python :: add title to relplot seaborn 
Python :: tkinter copy paste 
Python :: python string find 
Python :: how to have player input in python 
Python :: print a string with spaces between characters python 
Python :: python get env 
Python :: scikit learn roc curve 
Python :: exclude serializer 
Python :: create button in pyqt 
Python :: for enumerate python 
Python :: list get every 2nd element 
Python :: how to get python list length 
Python :: openpyxl read cell value 
Python :: days to int 
Python :: concatenate string and int python 
Python :: np.r_ 
Python :: hungry chef 
Python :: activate venv 
Python :: what is += python 
Python :: python print all variables in memory 
Python :: how to username in python? 
Python :: split pdf python 
Python :: getsizeof python 
Python :: mapping with geopandas 
Python :: pyaduio 
Python :: python constant 
Python :: (models.W042) Auto-created primary key 
ADD CONTENT
Topic
Content
Source link
Name
6+5 =