0% found this document useful (0 votes)
49 views

Python Strings1

The document contains code snippets demonstrating various string manipulation operations in Python like: 1. Swapping the first two characters of two input strings and concatenating them. 2. Extracting the first two and last two characters of an input string or empty string if length is less than 2. 3. Removing characters at odd index positions from a given string. 4. Displaying a string in upper, lower, and capitalized cases. 5. Reversing a string, slicing strings, accessing list elements with negative indexes. 6. Sorting a dictionary by values, adding keys to a dictionary, merging multiple dictionaries. 7. Extracting portions of a string like first,

Uploaded by

Harish Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Python Strings1

The document contains code snippets demonstrating various string manipulation operations in Python like: 1. Swapping the first two characters of two input strings and concatenating them. 2. Extracting the first two and last two characters of an input string or empty string if length is less than 2. 3. Removing characters at odd index positions from a given string. 4. Displaying a string in upper, lower, and capitalized cases. 5. Reversing a string, slicing strings, accessing list elements with negative indexes. 6. Sorting a dictionary by values, adding keys to a dictionary, merging multiple dictionaries. 7. Extracting portions of a string like first,

Uploaded by

Harish Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

In [2]: # get a single string from two given strings, separated by a space and swap the first two

characters of each string.


# i/p: abc, xyz
# o/p: xyc, abz
def chars(a, b):
x = b[:2] + a[2:]
y = a[:2] + b[2:]

return x + ' ' + y


print(chars('abc', 'xyz'))

xyc abz

In [4]: # get a string made of the first 2 and last 2 characters of a given string. If the string length is less than 2, return the empty string instead.
def string_both_ends(str):
if len(str) < 2:
return ''

return str[0:2] + str[-2:]

print(string_both_ends('w3resource'))
print(string_both_ends('w3'))
print(string_both_ends('w'))

w3ce
w3w3

In [5]: # Remove the characters which have odd index values of a given string
def values(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result

print(values('harishreddy'))
print(values('revanthreddy'))

hrsrdy
rvnhed

In [1]: # Display an input string in upper and lower cases


str = input("Enter a string:")
print("My language is:",str.upper()) # all letters will be in upper case
print("My name is:",str.lower()) # all letters will be in lower case
print(str.capitalize())# only first letter capitalize

Enter a string:HarishREDdy
My language is: HARISHREDDY
My name is: harishreddy
Harishreddy

In [8]: str = "python"


print(str[::-1])
print(str[:-2:-3])
print(str[:-1:-4])

nohtyp
n

In [11]: list = [(1,2),(2,3),(4,5),(5,6)]


list[1::-3]

[(2, 3)]
Out[11]:

In [14]: string = "harishreddy"


string[::-1]

'ydderhsirah'
Out[14]:

In [15]: string[0:8:2]

'hrsr'
Out[15]:

In [16]: list[0:-3:-1]

[]
Out[16]:

In [60]: string[-1:-9:-3]

'yes'
Out[60]:

In [17]: string[:-1:]

'harishredd'
Out[17]:

In [18]: import itertools

In [19]: print(''.join(itertools.islice(string, 3, 7)))

ishr

In [20]: my_list = [1, 2, 3, 4, 5]


print(my_list[::-2])

[5, 3, 1]

In [21]: print(my_list[::2])

[1, 3, 5]

In [22]: print(my_list[1:4:2])

[2, 4]

In [23]: import operator


d = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print('Original dictionary : ',d)
sorted_d = sorted(d.items(), key=operator.itemgetter(1))
print('Dictionary in ascending order by value : ',sorted_d)
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in descending order by value : ',sorted_d)

Original dictionary : {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}


Dictionary in ascending order by value : [(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
Dictionary in descending order by value : {3: 4, 4: 3, 1: 2, 2: 1, 0: 0}

In [24]: # Add a key to dictionary


d = {0:10, 1:20}
print(d)
d.update({2:30})
print(d)

{0: 10, 1: 20}


{0: 10, 1: 20, 2: 30}

In [25]: dic1={1:10, 2:20}


dic2={3:30, 4:40}
dic3={5:50,6:60}
dic4 = {}
for d in (dic1, dic2, dic3): dic4.update(d)
print(dic4)

{1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

In [30]: # Create a string made of the first, middle and last character
str1 = "Harish"
print("Original Character",str1)
res = str1[0]
print(res)
l = len(str1) # string size
mi = int(l/2) # middle index number
print("middle number",mi)
res = res+str1[mi]
print(res)# get middle character and add it to the result
res = res+str1[l-1] # get last character and add it to the result
print("New string:",res)

Original Character Harish


H
middle number 3
Hi
New string: Hih

In [5]: # Create a string made of the middle three characters


str2 = "JhonDipPeta"
print(str2[4:7])

# (or)

def get(str2):
print("original string",str2)
mi = int(len(str2)/2)
print("middle character:",mi)
res = str2[mi-1:mi+2]
print("Middle characters are:",res)
get("JhonDipPeta")
get("JaSonAy")

Dip
original string JhonDipPeta
middle character: 5
Middle characters are: Dip
original string JaSonAy
middle character: 3
Middle characters are: Son

In [34]: # Append new string in the middle of a given string


def append_middle(s1,s2):
print("original strings are:",s1,s2)
# middle index number of s1
mi = int(len(s1)/2)
print(mi)
# get character from 0 to the middle index number from s1
x = s1[:mi:]
print(x)
# concatenate s2 to it
x = x + s2
print(x)
# append remaining characters from s1
x = x + s1[mi:]
print("after appending new string in the middle:",x)

append_middle("Ault", "Kelly")

original strings are: Ault Kelly


2
Au
AuKelly
after appending new string in the middle: AuKellylt

In [7]: # Create a new string made of the first, middle, and last characters of each input string
# s1 = "America" s2 = "Japan"
# o/p: AJrpan
def mix_string(s1,s2):
# get first character from both string
first_char = s1[0] + s2[0]
print("first character:",first_char)
# get middle character from both string
middle_char = s1[int(len(s1)/2):int(len(s1)/2) + 1] + s2[int(len(s2) / 2):int(len(s2) / 2) + 1]
print("middle character:",middle_char)
# get last character from both string
last_char = s1[len(s1) - 1] + s2[len(s2) - 1]
print("last character:",last_char)
# add all
res = first_char + middle_char + last_char
print("Mix String is ", res)

s1 = "America"
s2 = "Japan"
mix_string(s1, s2)

first character: AJ
middle character: rp
last character: an
Mix String is AJrpan

In [8]: # Arrange string characters such that lowercase letters should come first
# i/p: PyNaTive o/p: yaivePNT
str1 = "PyNaTive"
print("original string:",str1)
lower = []
upper = []
for char in str1:
if char.islower():
# add lower characters to lower list
lower.append(char)
else:
# add upper characters to upper list
upper.append(char)
# join both the lists
sorted_str = ''.join(lower + upper)
print("res:",sorted_str)

original string: PyNaTive


res: yaivePNT

In [9]: # Count all letters, digits, and special symbols from a given string
str = input("Enter a string:")
alphabets = numbers = special_characters = 0

for i in range(len(str)):
if(str[i].isalpha()):
alphabets = alphabets+1
elif(str[i].isdigit()):
numbers = numbers+1
else:
special_characters = special_characters+1

print("Total number of alphabets:",alphabets)


print("Total number of numbers:",numbers)
print("Total number of special_characters:",special_characters)

Enter a string:@!#HArish3217#
Total number of alphabets: 6
Total number of numbers: 4
Total number of special_characters: 4

In [76]: # another way


def find_digits_chars_symbols(str):
char_count = 0
digit_count = 0
symbol_count = 0
for char in str:
if char.isalpha():
char_count += 1
elif char.isdigit():
digit_count += 1
# if it is not letter or digit then it is special symbol
else:
symbol_count += 1

print("Chars =", char_count, "Digits =", digit_count, "Symbol =", symbol_count)

str = "P@yn2at&#i5ve"
print("total counts of chars, Digits, and symbols")
find_digits_chars_symbols(str)

total counts of chars, Digits, and symbols


Chars = 8 Digits = 2 Symbol = 3

In [12]: # Create a mixed String using the following rules


s1 = "Abc"
s2 = "Xyz"

# get string length


a = len(s1)
b = len(s2)

# get length of a bigger string


length = a if a > b else b
res = ""

# reverse s2
s2 = s2[::-1]

# iterate string
# s1 ascending and s2 descending
for i in range(length):
if i < a:
res = res + s1[i]
if i < b:
res = res + s2[i]

print(res)

AzbycX

In [78]: # check if two strings are balanced. For example, strings s1 and s2 are balanced if all the characters in the s1 are present in s2. The character’s
def string_balance_test(s1, s2):
res = True
for char in s1:
if char in s2:
continue
else:
res = False
return res

s1 = "Yna"
s2 = "PYnative"
res = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", res)

s1 = "Ynf"
s2 = "PYnative"
res = string_balance_test(s1, s2)
print("s1 and s2 are balanced:", res)

s1 and s2 are balanced: True


s1 and s2 are balanced: False

In [79]: # Find all occurrences of a substring in a given string by ignoring the case
str1 = "Welcome to USA. usa awesome, isn't it?"
str1 = str1.count("USA")
print(str1)

#(or)

str1 = "Welcome to USA. usa awesome, isn't it?"


sub_string = "USA"

# convert string to lowercase


temp = str1.lower()

# use count function


count = temp.count(sub_string.lower())
print("The USA count is:", count)

1
The USA count is: 2

In [80]: # Calculate the sum and average of the digits present in a string
str = "Harish@#$%6!78201"
total = 0
count = 0

for char in str:


if char.isdigit():
total += int(char)
count += 1

Average = total/count
print("Sum is",total, "Average is",Average)

Sum is 24 Average is 4.0

In [81]: # by using regular expression


import re

str = "PYnative29@#8496"
digit_list = [int(num) for num in re.findall(r'\d', str)]
print('Digits:', digit_list)

# use the built-in function sum


total = sum(digit_list)

# average = sum / count of digits


avg = total / len(digit_list)
print("Sum is:", total, "Average is ", avg)

Digits: [2, 9, 8, 4, 9, 6]
Sum is: 38 Average is 6.333333333333333

In [82]: # count occurrences of all characters within a string


str1 = "Apple"

# create a result dictionary


char_dict = dict()

for char in str1:


count = str1.count(char)
# add / update the count of a character
char_dict[char] = count
print('Result:', char_dict)

Result: {'A': 1, 'p': 2, 'l': 1, 'e': 1}

In [83]: # Reverse a given string


str = "Harish"
str = str[::-1]
print(str)

#(or)
str = "Harish"
str = ''.join(reversed(str))
print(str)

hsiraH
hsiraH

In [84]: # Find the last position of a given substring


str1 = "Emma is a data scientist who knows Python. Emma works at google."
index = str1.rfind("Emma")
print(index)

43

In [85]: # Remove empty strings from a list of strings


str = ["Harish","Reddy","","Ganesh",None,"abcd"]
res_list = []
for s in str:
# check for empty string
if s:
res_list.append(s)
print(res_list)

['Harish', 'Reddy', 'Ganesh', 'abcd']

In [2]: #2 using inbuilt function


str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]

# use built-in function filter to filter empty value


new_str_list = list(filter(None, str_list))

print("After removing empty strings:",new_str_list)

After removing empty strings: ['Emma', 'Jon', 'Kelly', 'Eric']

In [90]: # Another Method


str_list = ["Emma","Jon","","Kelly", "None","Eric",""]
res = ' '.join(str_list).split()
print(res)

['Emma', 'Jon', 'Kelly', 'None', 'Eric']

In [1]: # Remove special symbols / punctuation from a string


import string

str1 = "/*Jon is @developer & musician"


print("Original string is ", str1)

new_str = str1.translate(str.maketrans('', '', string.punctuation))

print("New string is ", new_str)

Original string is /*Jon is @developer & musician


New string is Jon is developer musician

In [5]: # Another method


import re

str1 = "Harish?* Reddy/@ C*&"


print("Original string is: ", str1)

# replace special symbols with ''


res = re.sub(r'[^\w\s]', '', str1)
print("New string is: ", res)

Original string is: Harish?* Reddy/@ C*&


New string is: Harish Reddy C

In [6]: # Removal all characters from a string except integers


str = "Hi I am 27 years old born in 1995"
res = "".join([item for item in str if item.isdigit()])
print(res)

271995

In [12]: # Find words with both alphabets and numbers


str1 = "Harish24 Is Reddy2"
print("The Original String is:",str1)
res = []
# split string on white spaces
temp = str1.split()
print(temp)

# Words with both alphabets and numbers


# isdigit() for numbers + isalpha() for alphabets
# use any() to check each character
for item in temp:
if any(char.isalpha() for char in item) and any(char.isdigit() for char in item):
res.append(item)
print("words with alphabets and numbers:",res)
# for i in res:
# print(res)

The Original String is: Harish24 Is Reddy2


['Harish24', 'Is', 'Reddy2']
words with alphabets and numbers: ['Harish24', 'Reddy2']

In [17]: # Replace each special symbol with # in the following string


str1 = "/Harish@ Reddy? Chapp*&idi%"
print("Original string:",str1)

replace_char = '#'
# string.punctuation to get the list of all special symbols
for char in string.punctuation:
str1 = str1.replace(char,replace_char)

print("After replacing:",str1)

Original string: /Harish@ Reddy? Chapp*&idi%


After replacing: #Harish# Reddy# Chapp##idi#

In [19]: # to count vowels and consonant


n = "Harish"
vow = 0
con = 0
for i in range(len(n)):
if n[i] in ['a','e','i','o','u']:
vow = vow + 1
else:
con = con + 1
print("Total vowels are:", vow)
print("Total conconants are:", con)

Total vowels are: 2


Total conconants are: 4

In [20]: # remove duplicates in a string.


n = input("Enter a Word ")
x = []
for i in range(len(n)):
if n[i] not in x:
x.append(n[i])
else:
pass
for i in range(len(x)):
print(x[i], end=" ")

Enter a Word Haariisshh


H a r i s h

In [21]: # count the number of letters in a word.


n = input("Enter a string ")
count = 0
for i in range(len(n)):
count = count + 1
print(count)

Enter a string Harish Reddy


12

In [22]: # convert lower to upper and upper to lower


num = input("Enter a String ")
x = []
for i in range(len(num)):
if num[i].isupper():
x.append(num[i].lower())
elif num[i].islower():
x.append(num[i].upper())

# printing result
for i in range(len(x)):
print(x[i], end=' ')

Enter a String HaRIsh REddY


h A r i S H r e D D y

In [23]: # search word in str


str = "HARISH"
if "H" in str:
print(True)
else:
print(False)

True

In [26]: list = ["harish","reddy","abcd"]


if "xyz" in list:
print(True)
else:
print(False)

False

In [29]: # sort letters of word by lower to upper case format.


str = 'pytHOnloBBy'
lower = []
upper = []
for i in range(len(str)):
if str[i].islower():
lower.append(str[i])
else:
upper.append(str[i])

# printing result
result = ' '.join(lower+upper)
print(result)

p y t n l o y H O B B

In [32]: def get(roll):


x = [12,24,25,26,33,45]
if roll in x:
print(f"Roll number {roll} is present")
else:
print(f"Roll number {roll} is not present")

roll = int(input("Enter Roll Number:"))


get(roll)

Enter Roll Number:41


Roll number 41 is not present

You might also like