~/python/python-string-fun.md

Python 3 - Fun with Python String

1 min readMay 14, 2019by Gorav Singal#python-3#python-string#python
// TL;DR

Use Python string methods like startswith(), 'in' operator for substring checks, and string slicing for efficient string manipulation and comparison.

Python 3 - Fun with Python String

This post some useful tips of using strings, and some issues while dealing with strings

Hope, you have seen Python string format

Check if a string starts with some sequence of characters

to_search = 'my_name'
my_var = 'my_name_is_gorav'
if my_var.startswith(to_search):
    print('Found')

Get substring delimited by some character or string

Example, you have a string:

my_var = 'Name:GyanByte'

You want to have anything after colon

name = my_var.split(':')[1]

Get first letter capital of string

Example: You have some long string like:

name = 'SERVICE_CLOUD_ACCOUNTS'

And, I want something like:

ServiceCloudAccounts

Then, use this code:

new_name = name.title().replace('_', '')

title() method will give you Service_Cloud_Accounts, then we have to remove any other characters we want

Remove any whitespaces around a string, i.e trim

my_str.strip()

Remove multiple spaces with single space

Your string has multiple spaces in between, and you want to convert them into one only.

import re
s = 'hey,    i have  multiple    spaces'
re.sub("\s+", " ", s);

# Output
'hey, i have multiple spaces'

How to add Curly-braces to string in string format

It works perfectly find with following cases

print('{hi}')

print('{hi} %s' %('hi'))

But, not with

website='GyanByte.com'
print(f'hi { {website} .com}')

You have to use Double Curly-braces

website='GyanByte.com'
{% raw %}
print(f'hi {{ {website} .com}}')
{% endraw %}

Get whole string except first letter, or get anything after first character

s = 'GyanByte'
s[1:]
#Output: yanBlog

Get whole string except last letter

s = 'GyanByte'
s[:-1]

$ subscribe --weekly

One deep dive a week, in your inbox

System design, AI engineering, trading systems and interview prep. Tested code, real numbers. Free, and you can unsubscribe any time.

or read it on gyanbyte.substack.com

Share

Related Posts

How to Solve Circular Import Error in Python

How to Solve Circular Import Error in Python

Introduction To give some context, I have two python files. (Both in same folder…

Python 3 - Magical Methods and Tricks with extremely useful methods

Python 3 - Magical Methods and Tricks with extremely useful methods

This post will show some really awesome tricks in python. Get the power of a…

Python 3 - Format String fun

Python 3 - Format String fun

This post is dedicated for cases where we intend to append a variable value in a…

Understanding and Solving pylint errors for Python 3

Understanding and Solving pylint errors for Python 3

Pylint is an excellent tool to have good quality code. This post is not about…

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Python SMTP Email Code - How to Send HTML Email from Python Code with Authentication at SMTP Server

Introduction This post has the complete code to send email through smtp server…

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Python Build Quality Gates with Pylint and Unittest Coverage Thresholds

Introduction It is very important to introduce few process so that your code and…

Latest Posts

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

How to Stay Valuable as a Software Engineer in the AI Era: A Practical Playbook

In the previous article I argued that AI is not killing software engineering…

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

How to Review AI-Generated Code: A Checklist for Catching What the Model Missed

A few months back I approved a PR that was almost entirely AI-generated. It…

How to Debug AI-Generated Code: Understand First, Fix Last

How to Debug AI-Generated Code: Understand First, Fix Last

In the last article I wrote about reviewing AI code before it goes in. This one…

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

The Future of Software Engineering: What AI Changes, What Stays, and Where the Jobs Go

Every few weeks somebody sends me a scary headline — “AI will replace all…

The Transactional Outbox Pattern: Never Lose an Event Again

The Transactional Outbox Pattern: Never Lose an Event Again

This is one of those patterns that looks like nothing until you get burnt once…

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Event Sourcing, Explained: Store What Happened, Not Just the Final State

Here is a question I like to ask in interviews: your bank account shows a…