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

define a string in python

string1 = "something"
string2 = 'something else'
string3 = """
something
super
long
"""
Comment

python strings

# concatenating strings just means combining strings together
# it is used to add one string to the end of another
# below are two exmaples of how concatenation can be used 
# to output 'Hello World':

# example 1:
hello_world = "Hello" + " World"
print(hello_world)

>>> Hello World

# example 2:
hello = "Hello"
print(hello + " World")

>>> Hello World
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

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

all string methods in python

# Look into this Python documentation link
# https://docs.python.org/3/library/stdtypes.html#string-methods
# if not, use dir for a sting object
stuff = 'Hello World!'
print(type(stuff))
print(dir(stuff))
Comment

python strings

type('Hellloooooo') # str

'I'm thirsty'
"I'm thirsty"
"
" # new line
"	" # adds a tab

'Hey you!'[4] # y
name = 'Andrei Neagoie'
name[4]     # e
name[:]     # Andrei Neagoie
name[1:]    # ndrei Neagoie
name[:1]    # A
name[-1]    # e
name[::1]   # Andrei Neagoie
name[::-1]  # eiogaeN ierdnA
name[0:10:2]# Ade e
# : is called slicing and has the format [ start : end : step ]

'Hi there ' + 'Timmy' # 'Hi there Timmy' --> This is called string concatenation
'*'*10 # **********
Comment

Python Strings

#!/usr/bin/python

str = 'Hello World!'

print str          # Prints complete string
print str[0]       # Prints first character of the string
print str[2:5]     # Prints characters starting from 3rd to 5th
print str[2:]      # Prints string starting from 3rd character
print str * 2      # Prints string two times
print str + "TEST" # Prints concatenated string
Comment

a python string

a_string = "this is a string"
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 :: sum along axis python 
Python :: how to get the last value in a list python 
Python :: django create superuser from script 
Python :: conda cassandra 
Python :: python urlparse get domain 
Python :: extract bigrams python 
Python :: hover show all Y values in Bokeh 
Python :: start virtual environment python linux 
Python :: how to get wikipedia photos using wikipedia module ip python 
Python :: pandas read_excel 
Python :: lambda function dataframe 
Python :: Python round to only two decimal 
Python :: python requests no certificate example 
Python :: pip install opencv 
Python :: get html input in django 
Python :: py to exe 
Python :: uninstall python3 from source on centos 7 
Python :: python find string count in str 
Python :: shallow copy in python 
Python :: pytest logcli to write to file 
Python :: how to use dictionary in python 
Python :: calculate pointbiseral correlation scipy 
Python :: open url from ipywidgets 
Python :: python check for alphanumeric characters 
Python :: register template tag django 
Python :: python add item to list 
Python :: python index method 
Python :: skimage local threshold 
Python :: python is space 
Python :: python code to get wifi 
ADD CONTENT
Topic
Content
Source link
Name
4+7 =