My Coding > Programming language > Python > String works in Python

String works in Python

Strings in Python

Python give a lot of different tools to work with strings. But every time, before using any of these tools, think twice, maybe it is better to use regular expressions? In many cases regular expressions are better.

Simple string manipulations

String initialisation

Stricng can be initialized in different quotes


a = 'String a'
b = "String b"
c = '''String c'''
d = """String a"""
e = 'Love\'it'  # to preserve quotes inside string - use back slash
f = "Love\'it"  # or use different quotes
g = '''multi
line string'''  # use triple quotes for multi line string    
h = "big\ttab"  # use special symbols with bacl slash
i = r"big\ttab" # raw input - back slahs will be ignored

String concatenation

Basic string concatenation in Python


print('abc'+'def') # abcdef
a='abc'
b='def'
print(a*3)         # abcabcabc
print(a*2.5)       # TypeError
print(a*b)         # TypeError
print(a + 34)      # TypeError

Python string search

Very easy to understand what these simple searches are doing


print("abc" in "abcdefghabcdefgh")    # True
print("abd" in "abcdefghabcdefgh")    # False
print("abcdabcd".find("bcd"))         # 1 (or -1 if not found)
print("abcdabcd".rfind("bcd"))        # 5 (or -1 if not found)
print(str.find.__doc__)               # Documaentation about find
print("abcdabcd".find("bcd",3))       # 5 (use search from position 3)
print("abcdabcd"[1:].find("bcd"))     # 0!!! - search is performed within slice!!!
print("abcdabcd".index("bcd"))        # 1 - works as find, but (ValueError - if not found)
S = "AB_CD_EF_GH.jpg"
print(S.startswith("AB_"))            # True; can use tuple as parameter
print(S.endswith(".jpg"))             # True; can use tuple as parameter
print("abcdefghabcdefgh".count("abc"))# 2 - not interlapping fragments!!!!
print("ababa".count("aba"))           # 1 !!! - not interlapping fragments!!!!

String converting in Python

Always thing about regular expressions first. Again not much to comment onthese examples


S="This is a Text, this text is nice"
print(S.lower()) # this is a text, this text is nice
print(S.upper()) # THIS IS A TEXT, THIS TEXT IS NICE
print(S.count("this"))          # 1
print(S.lower().count("this"))  # 2
s = "1,2,3,4"
print(s.replace(",",", "))   # 1, 2, 3, 4
print(s.replace(",",", ",2)) # 1, 2, 3,4
print(s.split(","))          # ['1', '2', '3', '4']
print(s.split(",", 2))       # ['1', '2', '3,4']
s = "1\n2\t3 4     5   "
print(s.split())             # ['1', '2', '3', '4', '5'] - split without parameters
s = "_&__1, 2, 3__&_&_&"
print(s.rstrip("&_"))        #_&__1, 2, 3
print(s.lstrip("&_"))        # 1, 2, 3__&_&_&
print(s.strip("&_"))         # 1, 2, 3
L = ["a", "b", "c"]
print("".join(L))            # abc
print(" ".join(L))           # a b c
print(", ".join(L))          # a, b, c

String Formatting in Python

Using template for simple generating of nice formatter output


template = "Move {} from {}"
print(template.format("Village", "Maria"))  #Move Village from Maria

template = "Move {1} from {0}"
print(template.format("Village", "Maria"))  #Move Maria from Village

template="{capital} is the capital of {country}"
print(template.format(capital="London", country="England")) # London is the capital of England

import requests
template = "Response from {0.url} with code {0.status_code}" # call for ofject attributes in template
res = requests.get("https://wikipedia.org/")
print(template.format(res)) # Response from https://www.wikipedia.org/ with code 200

Formatting of digital information


x=1.239565432
print("{:.3}".format(x)) # 1.24!!! - this is proper rounding

Read more about strings here: https://docs.python.org/3/library/stdtypes.html#text-sequence-type-str


Published: 2021-09-29 09:50:56
Updated: 2021-09-30 02:05:56

Last 10 artitles


9 popular artitles

© 2020 MyCoding.uk -My blog about coding and further learning. This blog was writen with pure Perl and front-end output was performed with TemplateToolkit.