4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

文字列補間チートシート

Posted at

すぐ記法を忘れてしまうので、私が最近よく使う言語の String Interpolation Cheat Sheet です。

言語 記法 null文字列の出力結果
Kotlin "${foo}" "null"
Swift "\(foo)" "null"
TypeScript  `${foo}`  "null"
Ruby "#{foo}" ""
Python f"{foo}" "None"

Kotlin

val str: String = "nya"
val nullableStr: String? = "neko"
val nullStr: String? = null
print("Hello ${str}, ${nullableStr} and ${nullStr}")
Hello nya, neko and null

Swift

let str: String = "nya"
let nullableStr: String? = "neko"
let nullStr: String? = nil
print("Hello \(str), \(nullableStr) and \(nullStr)")
Hello, nya, Optional("neko") and nil

なお Optional 型を使おうとすると String interpolation produces a debug description for an optional value; did you mean to make this explicit? という Compiler Warning が出る。

TypeScript

バージョン 1.4 以上

interface Hoge {
  str: string
  optionalStr?: string
  nullStr: string | null
  undefinedStr?: string
}

const hoge: Hoge = { str: "nya", optionalStr: "neko", nullStr: null }
console.log(`Hello ${hoge.str}, ${hoge.optionalStr}, ${hoge.nullStr} and ${hoge.undefinedStr}`)
Hello nya, neko, null and undefined

Ruby

str = "nya"
nullStr = nil
puts "Hello #{str} and #{nullStr}"
Hello nya and 

Python

バージョン 3.6 以上。

str = "nya"
nullStr = None
print(f"Hello {str} and {nullStr}")
Hello nya and None
4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?